添加方法 paint() 后,JPanel 的背景色替换为灰色

Background color for JPanel replaced by grey when method paint() added

我编写了以下基本 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(一个java1.0 - 1.1方法)调用了JComponents中的paintBackground。当您覆盖它时,它不会调用所有的 swing paint 方法。但是如果你加上super.paint(g),它看起来会像以前一样。

另外 - 请注意,JFrame 中的默认 ContentPane 已经是一个 JPanel。与其用 JPanel 替换 ContentPane,不如调用:

((JPanel) myFrame.getContentPane()).setBackground(Color.blue);

您不应覆盖 paint,而应覆盖 paintComponent。问题仍然会发生,所以你需要调用 super.paintComponent(g)

所以将您的绘画方法更改为以下内容。

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.
   }

}

并且不要在Chart1class中分classJFrame。这是不好的做法。使用实例。

JFrame frame = new JFrame();