I was wondering what the best practice is to switch between windows for a Java Swing application. I can either create a JFrame for each window, or create a new JPanel for each window and switch them within one JFrame.
4 Answers
Best practice is switching between panels. First advantage is efficiency, second is the fact that everyone is used with only static windows which stay in positions and sizes.
But I'm quite sure that there will be more opinions but for me switching panels is more practicable.

- 401
- 4
- 12
You could use instances of JTabbedPane
. This allows you to switch between JPanels
and keeps everything very organized. Also a big plus is that the mouse handling is already done for you. Here's a quick example that shows you how easy it is to use JTabbedPane
.
public class TabbedDemo
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
JTabbedPane tabbed = new JTabbedPane();
JPanel panel1 = new JPanel();
panel1.add(new JLabel("Panel 1"));
tabbed.addTab("Panel 1", panel1);
JPanel panel2 = new JPanel();
panel2.add(new JLabel("Panel 2"));
tabbed.addTab("Panel 2", panel2);
JPanel panel3 = new JPanel();
panel3.add(new JLabel("Panel 3"));
tabbed.addTab("Panel 3", panel3);
frame.add(tabbed);
frame.setPreferredSize(new Dimension(400,400));
frame.setVisible(true);
}
}
And you're resulting GUI looks like this.

- 254
- 2
- 12
Depends on the application. For the most part common practice is to place a JPanel
within a JFrame
anyway so the second option is probably best and it would be less cluttered.

- 2,231
- 1
- 14
- 18
Ideally Swing
applications are supposed to have only a single JFrame
. You should switch between JPanel
or use JInternalFrame
.
And there are Modal dialogs
that are best practice for interacting with user.

- 289
- 2
- 7