问题描述
我编写了下面的Java Swing基本示例,它是一个具有蓝色背景的JPanel:
public class Chart1 extends JFrame {
private MainPanel1 main;
public Chart1() throws InterruptedException {
setSize(600,500);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// CREATE AND ADD MAIN PANEL
main = new MainPanel1();
this.getContentPane().add(main,BorderLayout.CENTER);
// DRAW WINDOW
this.setVisible(true);
}
}
public class MainPanel1 extends JPanel {
public MainPanel1() {
setBackground(Color.BLUE);
}
}
我得到以下结果:
到目前为止,很好。
现在,我添加一个paint()
方法。源代码如下:
public class MainPanel1 extends JPanel {
public MainPanel1() {
setBackground(Color.BLUE);
}
public void paint(Graphics g) {
}
}
然后即使在paint()
中不做任何操作,我的背景都是灰色的,为什么?我该如何解决?
解决方法
答案是paint(一种Java 1.0-1.1方法)在JComponents中调用paintBackground。当您覆盖它时,它并不会调用所有的swing paint方法。但是,如果添加super.paint(g),它将看起来像以前一样。
也-请注意,JFrame中的默认ContentPane已经是JPanel。不用用您的JPanel替换ContentPane,您可以调用:
((JPanel) myFrame.getContentPane()).setBackground(Color.blue);
,
您不应覆盖asyncio.sleep
,而应覆盖paint
。该问题仍然会发生,因此您需要调用paintComponent
因此将您的绘画方法更改为以下内容。
super.paintComponent(g)
请勿在{{1}}类中将public class MainPanel1 extends JPanel {
public MainPanel1() {
setBackground(Color.BLUE);
}
public void paintComponent(Graphics g) {
// The following statement ensures that
// the background color will be applied
// as well as other preparations for
// doing graphics.
super.paintComponent(g);
// If you have other graphics
// code,add it here.
}
}
子类化。这是不好的做法。使用实例。
JFrame