Der*_*ter 0 java graphics swing paint jbutton
我正在尝试绘制背景,然后将按钮放到面板上.如果没有绘制方法,按钮将正确放置在屏幕上,但是当绘制方法存在时,按钮不会显示,直到鼠标悬停在它们上面.我无法弄清楚为什么会这样.谢谢
这是在构造函数中:
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++;
}
}
Run Code Online (Sandbox Code Playgroud)
然后是:
@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)
}
Run Code Online (Sandbox Code Playgroud)
因为你没有调用super.paint(g)子组件所以不要画画.
有关详细信息,请阅读" 关于绘制机制的详细介绍"中的Swing教程中的部分.
但是你不应该重写paint().自定义绘画是通过覆盖paintComponent()方法完成的.
代码应该是:
public void paintComponent(Graphics g)
{
super.paintComponent(...);
...
Run Code Online (Sandbox Code Playgroud)