what is the purpose of JFrame setBackground

二次信任 提交于 2019-12-11 21:06:09

问题


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 :

  1. Why jf.getContentPane().setSize(300, 100); does not resize default JPanel , revealing JFrame background?

  2. Why JFrame has setBackground method if anyway you cannot see it and it is covered by default JPanel all 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 JFrame class is slightly incompatible with Frame. Like all other JFC/Swing top-level containers, a JFrame contains 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 the JFrame. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!