2

If the frame is placing on top of the content pane the exterior colour to the user is colour of JFrame. Here even i'm painting the frame after content pane but content pane colour will be displayed. Why?

public class GUI {
    public static void main(String[] args){
        JFrame frame = new JFrame();
        frame.setSize(300,300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        Color myColor = new Color(100,100,100);
        frame.setLocationRelativeTo(null);
        frame.getContentPane().setBackground(myColor);
        frame.setBackground(Color.red);

    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Bernard
  • 4,240
  • 18
  • 55
  • 88

1 Answers1

3

You shouldn't be setting the background of the JFrame itself. You CAN, yes, but it doesn't work very well.

It's got a content pane that covers the whole frame, so any color "underneath" will be covered up, as you've found.

All layout and styling should happen in the content pane.

You can set the content pane to a container of your choice, though, with a special layout or whatnot.


Also, when you say "painting the frame after the content pane" that's not actually happening. :) You're setting the background color after you set the background of the content pane, but it doesn't actually get repainted until its repaint flag is triggered by the application runtime.

Then it goes and checks what color is set, and paints. The order that you call the setters doesn't really matter.

Ben
  • 54,723
  • 49
  • 178
  • 224
  • But i thought the frame is placing on top of the content pane. – Bernard Nov 13 '12 at 03:50
  • 2
    Nope, content pane is INSIDE the frame. Frame is always top level. The content pane holds the content of the frame ;) – Ben Nov 13 '12 at 03:51
  • Thanks Steve for your answer, I'm little bit confused. Swing components has at least one top-level container. In my example which one is swing component and which one is the top level container? – Bernard Nov 13 '12 at 03:56
  • They're both swing components, and the JFrame is on a higher level than the content pane. Since it happens to be a JFrame, it is on the highest level, so it's the ultimate "top level container." Although, I'm not sure what contains the JFrame... – Ben Nov 13 '12 at 04:02
  • 1
    @Bernard You might like to check out [How to Use Root Panes](http://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html) which explains the basic container hierarchy of a top level window – MadProgrammer Nov 13 '12 at 04:19