绘画后组件不显示

Components don't show up after painting

我正在尝试绘制背景,然后将按钮放到面板上。如果没有 paint 方法,按钮会正确地放在屏幕上,但是当有 paint 方法时,按钮不会显示,直到鼠标悬停在它们上面。我不明白为什么会这样。谢谢

这是在构造函数中:

setBorder(new EmptyBorder(40, 40, 40, 40));
setSize(1600, 1000);
setLayout(new GridLayout(4, 0, 40, 40));

for(int r = 0; r < rows; r++){
        for(int c = 0; c < cols; c++){
            levels[r][c] = new JButton(String.valueOf(levelNum));
            levels[r][c].setMargin(new Insets(50, 50, 50, 50));
            levels[r][c].addActionListener(e);
            levels[r][c].setBackground(Color.MAGENTA);
            this.add(levels[r][c]);
            levelNum++;
        }
}

然后是:

@Override
public void paint(Graphics g){

    g.setColor(Color.CYAN);
    g.fillRect(0, 0, this.getWidth(), this.getHeight());

    ... (just some basic fillRect()'s and things)
}

因为您不调用 super.paint(g),所以不会绘制子组件。

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

但是无论如何你都不应该覆盖 paint() 。自定义绘画是通过重写 paintComponent() 方法完成的。

代码应该是:

public void paintComponent(Graphics g)
{
    super.paintComponent(...);
    ...