When you create JFrame
instance, you have setBackground
method available from this instance. However, regardless to what color you try to put there, you`ll receive gray background color.
This happens (as i understood), because default JPanel
instance is automatically created inside JFrame
and lays over it . So, to get color set, you need to call
JFrame.getContentPane().setBackground(Color.RED);
that actually calls setBackground
of default JPanel
, that exists inside JFrame
.
I also tried to do next :
JFrame jf = new JFrame();
//I expect this will set size of JFrame and JPanel
jf.setSize(300, 500);
//I expect this to color JFrame background yellow
jf.setBackground(Color.yellow);
//I expect this to shrink default JPanel to 100 pixels high,
//so 400 pixels of JFrame should became visible
jf.getContentPane().setSize(300, 100);
//This will make JPanel red
jf.getContentPane().setBackground(Color.RED);
After this set of code, I am having solid red square of JFrame
size , i.e. 300 x 500.
Questions :
Why
jf.getContentPane().setSize(300, 100);
does not resize defaultJPanel
, revealingJFrame
background?Why JFrame has
setBackground
method if anyway you cannot see it and it is covered by defaultJPanel
all the time?