Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

swing

jframe

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?

like image 491
Tomas Aschan Avatar asked Jan 08 '12 02:01

Tomas Aschan


People also ask

Can components be added directly to a frame?

When you add components directly to frame you actually are adding the components to a panel. So you have all the layout features of the panel. So in reality there is no difference for adding components to the frame or be using your own panel as the content pane of the frame.

Do you need a JPanel in JFrame?

Both JFrame and JPanel are important as a swing GUI cannot exist without these top-level containers. JFrame and JPanel both provide different methods to perform different GUI related functions.

Is a JFrame a component?

JFrame class is a type of container which inherits the java. awt. Frame class. JFrame works like the main window where components like labels, buttons, textfields are added to create a GUI.


1 Answers

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.

like image 113
Andrew Thompson Avatar answered Oct 31 '22 02:10

Andrew Thompson