簡體   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