2013-07-31 28 views
5

我将JPanel设置为我的JFrame的contentPane。无法在我的Swing程序中设置JPanel的背景。

当我使用:

jPanel.setBackground(Color.WHITE); 

的白色不适用。

但是当我使用:

jFrame.setBackground(Color.WHITE); 

它的工作...我的这种行为感到惊讶。它应该是相反的,不是吗?

SSCCE:

下面是一个SSCCE:

主类:

public class Main { 
    public static void main(String[] args) { 
     Window win = new Window(); 
    } 
} 

窗口类:

import java.awt.Color; 
import javax.swing.JFrame; 

public class Window extends JFrame { 
    private Container mainContainer = new Container(); 

    public Window(){ 
     super(); 
     this.setTitle("My Paint"); 
     this.setSize(720, 576); 
     this.setLocationRelativeTo(null); 
     this.setResizable(true); 
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     mainContainer.setBackground(Color.WHITE); //Doesn't work whereas this.setBackground(Color.WHITE) works 
     this.setContentPane(mainContainer); 
     this.setVisible(true); 
    } 
} 

容器类:

import java.awt.Graphics; 
import javax.swing.JPanel; 

public class Container extends JPanel { 
    public Container() { 
     super(); 
    } 
    public void paintComponent(Graphics g) { 
    } 
} 
+0

什么是JPanel的大小?它是否完全填充内容窗格? – bas

+0

为了更好的帮助,尽快发布[SSCCE](http://sscce.org/) – Reimeus

+0

我没有设置我的jPanel的大小。当我将它设置为contentPane时,我认为它自动与相应的jFrame大小相同。 – MarAja

回答

3

的原因很简单,包括以下行

super.paintComponent(g); 
当你重写paintComponent

public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
    } 

现在它完美地工作。

你应该一直这样做,除非你有一个非常具体的理由这样做。

[PS:颜色更改为红色或暗的东西,以发现其中的差别,因为有时候难以JFrame区分的默认灰色和白色的颜色]

+0

1+为好建议。 –

1

用我testcode它的工作原理,你预计它的工作方式:

public class Main { 

     public static void main(String[] args) { 

      JFrame f = new JFrame(); 
      f.setSize(new Dimension(400,400)); 
      f.setLocationRelativeTo(null); 

      JPanel p = new JPanel(); 
      p.setSize(new Dimension(20,20)); 
      p.setLocation(20, 20); 

      //comment these lines out as you wish. none, both, one or the other 
      p.setBackground(Color.WHITE); 
      f.setBackground(Color.BLUE); 

      f.setContentPane(p); 

      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      f.setVisible(true); 

     } 
     } 
+0

用户在他的特定代码中询问问题,而不是工作方法/代码。总之,您提出了一个替代方案。好。 –