面板没有边框

Panel doesn't have border

我正在做一个项目,我刚刚开始使用 GUI。因为这不是我最喜欢的主题,所以我很快就偶然发现了一些不太正确的东西。所有内容(PacmanGrid、PacmanScore)都显示正确,但我为 PacmanScore 面板写的边框!不管怎样,这是代码,希望有人能帮忙。

public class PacmanFrame extends JFrame{



public PacmanFrame() {
    this.setLayout(new BorderLayout());
    this.setTitle("Pacman");
    PacmanGrid p1=new PacmanGrid();
    PacmanScore p2 = new PacmanScore();


    this.add(p1,BorderLayout.CENTER);
    this.add(p2,BorderLayout.EAST);
    super.setDefaultCloseOperation(EXIT_ON_CLOSE);
    super.repaint();
    pack();
    super.setVisible(true);


}


public static void main(String[] args) {
    PacmanFrame p1 = new PacmanFrame();
}

 }

PacmanScore

public class PacmanScore extends JPanel{
private TitledBorder t3 = BorderFactory.createTitledBorder("Menu");
private Border etched = BorderFactory.createEtchedBorder(Color.WHITE, Color.white);


public PacmanScore() {
    setLayout(new FlowLayout());
    setPreferredSize(new Dimension(100,800));
    setBackground(Color.DARK_GRAY);
    t3.setBorder(etched);
    setBorder(t3);

    setVisible(true);
    setOpaque(true);


}

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D)g;
    super.paintComponent(g2);
    g2.setColor(Color.white);
    g2.drawString("Score: ", 20, 400);

}

}

PacmanGrid 也由 Panel 扩展,并使用预定义的模式绘制经典的 PacmanGrid。但我认为这无关紧要,因为问题显然出在 PacmanScore 面板上。如果有人需要,我会 post 代码。 提前致谢!

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D)g;
    super.paintComponent(g2);
    g2.setColor(Color.white);
    g2.drawString("Score: ", 20, 400);

}

您没有正确覆盖 paint(),因为您没有调用 super.paint(),因此没有绘制边框。

不要覆盖 paint()。自定义绘画是通过重写 paintComponent().

完成的

阅读 A Closer Look at the Paint Mechanism 上的 Swing 教程部分了解更多信息。

你为什么还要定制绘画?只需在面板中添加一个 JLabel。

此外,Swing 组件(顶级 windows 除外)默认可见,因此无需使面板可见。