简体   繁体   中英

Why JFrame colour is changing by changing content pane colour?

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

    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM