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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With