繁体   English   中英

添加方法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);
        
    }
}

我得到以下结果:

蓝色 JPanel

到现在为止还挺好。

现在我添加一个paint()方法。 源代码如下:

public class MainPanel1 extends JPanel {        
    
    public MainPanel1() {
        
        setBackground(Color.BLUE);
        
    }
    
    public void paint(Graphics g) {
    }

}

然后即使没有在paint()做任何事情,我也会得到灰色背景,为什么? 我怎样才能解决这个问题?

带油漆的 JPanel

答案是paint(一个java 1.0 - 1.1 方法)在JComponents 中调用paintBackground。 当您覆盖它时,它不会调用所有的摆动绘画方法。 但是如果你添加 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.
   }

}

并且不要在Chart1类中Chart1 JFrame 这是不好的做法。 使用实例。

JFrame frame = new JFrame();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM