What's the difference between:
public class Test {
public static void main(String[] args) {
JButton button= new JButton("1");
button.setVisible(true);
JPanel panel= new JPanel();
panel.add(button);
panel.setVisible(true);
JFrame frame = new JFrame();
frame.add(panel);
frame.setVisible(true);
frame.pack();
}
}
and
public class Test {
public static void main(String[] args) {
JButton button= new JButton("1");
button.setVisible(true);
JFrame frame = new JFrame();
frame.add(button);
frame.setVisible(true);
frame.pack();
}
}
I know that a JPanel is a container for GUI components but I really don't see the utility of use it. Certainly I'm very wrong but I'm starting with Swing, so... Why I should use a JPanel? What's really the purpose?
While JPanel is light and is used for organising Graphical User Interface (GUI) components. JFrame is a window used for creating independent GUI applications. While Jpanel is a space where one can put together a group of complex components or operations. Being a window, JFrame contains a title bar.
A panel provides space in which an application can attach any other component, including other panels. The default layout manager for a panel is the FlowLayout layout manager.
JPanel is a generic container that can hold other elements. It can be visible, changing the background color, the image model or having a border, or be invisible, only used for the hierarchy of the content. It is recommended not to place elements directly in a JFrame, but in a JPanel that is placed in a JFrame.
Why I should use a JPanel?
You use a JPanel for one or more of the following benefits:
GridLayout
for number pad, a CardLayout
for display panel where you can switch drawings).Usually I perceive a JFrame like a real life painting frame and JPanel like a piece of blank paper. We don't paint directly onto the frame. Instead, we paint on a piece of paper, and insert the paper into the frame. Painting directly on the frame is possible, but no one does that.
The same goes with JFrame and JPanel. We can add components directly to the frame, but usually we add it to the panel, then add the panel to the frame.
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