简体   繁体   中英

Should I add components to a JFrame or to its contentPane?

When I learned creating Java GUI:s in my first Java course, I was taught to create my windows as JFrame instances, and then add a JPanel to each JFrame and finally add all the GUI components to the JPanel :

class Example extends JFrame {
    Example() {
        JPanel panel = new JPanel();
        this.add(panel);

        // Create components here and add them to panel
        // Perhaps also change the layoutmanager of panel

        this.pack();
        this.setVisibility(true);
    }

    public static void main(String[] args) {
        new Example();
    }
}

I always though "well, this smells a little; I don't like creating an extra object just to be a container," but I didn't know any other way to do it so I just went on with it. Until recently, when I stumbled over this "pattern":

class AnotherExample extends JFrame {
    AnotherExample() {
        Container pane = this.getContentPane();

        // Add components to and change layout of pane instead

        this.pack();
        this.setVisibility(true);
    }

    public static void main(String[] args) {
        new AnotherExample();
    }
}

Still being quite new to Java, I feel better about the second approach just because it doesn't involve creating a JPanel just to wrap the other components. But what are the real differences between the approaches, except from that? Does any one of them have any great benefits over the other?

I prefer to create a JPanel (which, being a Swing container, can have a border) and set it as the content pane.

To get a JComponent out of the content pane requires casting, which has an even worse smell than creating an extra component.

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