我正在尝试绘制背景,然后将按钮放到面板上。如果没有绘制方法,按钮会正确放置在屏幕上,但是当绘制方法存在时,按钮不会显示,直到鼠标悬停在它们上面。我无法弄清楚为什么会这样。感谢
这是在构造函数中:
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)
}
答案 0 :(得分:5)
因为您没有调用super.paint(g)
,所以子组件不会被绘制。
阅读A Closer Look at the Painting Mechanism上的Swing教程中的部分以获取更多信息。
但是你不应该重写paint()。自定义绘画是通过覆盖paintComponent()
方法完成的。
代码应为:
public void paintComponent(Graphics g)
{
super.paintComponent(...);
...