What\'s the difference between:
public class Test {
public static void main(String[] args) {
JButton button= new JButton(\"1\");
button.
There is basically no visual difference in your two examples, but the UI is too poor for exhibiting a difference. A JPanel
is exactly what a panel is in real life, something used to display things inside it. It is generally used to contains different elements that you want to display in a given layout.
Grouping certain components together so you can manipulate groups of them within loops. Maybe to check if all text boxes within a region meet a certain requirement or to destroy them completely.
The purpose is to group components together.
Look at this web page for example. You could imagine a center panel with the question and answers laid out vertically, a right panel containing yet other panels: one for the blog, one for the job announcement, one for the related questions, and finally a south panel for the footer.
The footer panel can be reused in other pages than question pages.
The layout of the page as a whole is easier to understand and implement if you divide it into independant panels.
You can put more than one JPanel in the JFrame. JPanel is a conainer for you other components and can grouping it by logical features.
You can use a JPanel
to create a reusable building block of your user interface and maintain a single point of maintenance for all instances of it. Let's say you would create a JFrame
containing a diff view for two texts. The left and right view are lets say identical twins. It is way easier to create a panel twice and to add these two panels on the frame instead of adding all subsequent components twice into your frame directly.
Whenever you now have to change the view, let's say you want to add another button, or whatever you can do it at your panel and both - the left and right view will contain the changes immediately.
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.