问题
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, revealingJFramebackground?Why JFrame has
setBackgroundmethod if anyway you cannot see it and it is covered by defaultJPanelall the time?
回答1:
As per the class hierarchies of JFrame as shown below:
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
The method Frame#setBackground() is inherited from Frame and JFrame doesn't do override it.
What JFrame states:
The
JFrameclass is slightly incompatible with Frame. Like all other JFC/Swing top-level containers, aJFramecontains a JRootPane as its only child. The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by theJFrame. This is different from the AWT Frame case.
You can override default setBackground() of JFrame as shown below:
@Override
public void setBackground(Color color){
super.setBackground(color);
getContentPane().setBackground(color);
}
来源:https://stackoverflow.com/questions/24213483/what-is-the-purpose-of-jframe-setbackground