我将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) {
}
}
什么是JPanel的大小?它是否完全填充内容窗格? – bas
为了更好的帮助,尽快发布[SSCCE](http://sscce.org/) – Reimeus
我没有设置我的jPanel的大小。当我将它设置为contentPane时,我认为它自动与相应的jFrame大小相同。 – MarAja