Daniel Gurianov
Daniel Gurianov

Reputation: 551

what is the purpose of JFrame setBackground

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?

Upvotes: 0

Views: 614

Answers (1)

Braj
Braj

Reputation: 46861

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);
}

Upvotes: 2

Related Questions