Build a reusable Java Swing window with CardLayout
Keep the sidebar while Swing swaps content panels with CardLayout. A screen registry creates each panel the first time you open it.
I moved the restaurant list and detail views into one Swing window. The sidebar stays in place, and a screen registry creates each content panel on its first visit.
The example uses Java 17 and requires only the JDK. The RSIS references point to the refactor-v2 implementation.
Give the main window one job
My original restaurant list created a JFrame and positioned its controls with setBounds(). Opening a restaurant constructed a second frame. Both screens managed their own window placement and close action. A shared menu would have meant adding a copy to each frame. Original StoreList
The new RSIS window owns the parts shared by Explore, Recommendations, and Settings. Each screen supplies a content panel and chooses its own layout. The frame sets the position of the menu and handles the close action. A short confirmation can use an owned JDialog that returns the user to the same screen. Separate frames make sense when users need two independent documents open side by side.
| User interaction | Swing structure |
|---|---|
| Move through sections with a persistent menu | One JFrame with a CardLayout content area |
| Confirm an action and return to the current screen | An owned JDialog |
| Work with two documents in separate windows | Independent JFrame instances |
Keep the sidebar outside CardLayout
I put a BorderLayout on the root panel. The sidebar occupies WEST, where its preferred width can guide the layout. The router supplies a panel for CENTER, which takes the remaining space. Selecting a menu item changes the contents of that center panel. The sidebar remains in the root panel throughout the transition. MainFrame
BorderLayout allocates space to the sidebar and the content panel. Inside the content panel, CardLayout displays one child at a time. I register each card with a unique string key and pass it to show(parent, key). That call hides the previous card without removing it from the parent. Its text fields and scroll pane can keep their state. JDK 17 CardLayout documentation
Register screens and open them on demand
RsisApplication registers a screen factory for each route type. The first visit calls the factory and adds its panel to the card container. Later visits find the same panel by route type. The route instance carries the restaurant ID, so the detail panel can show restaurant 7 and then restaurant 8. Browsing the catalog leaves one detail panel in the card container. Screen registration · CardLayoutRouter
The router calls onLeave() on the previous screen, invokes onEnter(route) on the destination, shows its card, and notifies route listeners. The sidebar uses that notification to highlight the active menu item. A screen can close a subscription as you leave even though its panel stays in the container. I cover the interaction between the router and the list model in preserving search state.
Add a third menu item to a small example
Save this as SwingShell.java and run java SwingShell.java on a machine with a display. The example opens Explore first. Type something in the field, open Settings, and return. The text is still there because the app displays the same Explore panel again. The registry puts the key, label, and factory in one record. A single entry defines both the sidebar button and the card it opens. Swing creates and displays the window on the event dispatch thread.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import javax.swing.*;
public class SwingShell {
record Page(String id, String label, Supplier<JPanel> create) {}
public static void main(String[] args) {
SwingUtilities.invokeLater(SwingShell::open);
}
private static void open() {
List<Page> pages = List.of(
new Page("explore", "Explore", () -> page("Find a restaurant")),
new Page("settings", "Settings", () -> page("Application settings"))
);
CardLayout cards = new CardLayout();
JPanel content = new JPanel(cards);
JPanel sidebar = new JPanel(new GridLayout(0, 1, 0, 6));
JPanel navigation = new JPanel(new BorderLayout());
navigation.add(sidebar, BorderLayout.NORTH);
Set<String> mounted = new HashSet<>();
for (Page page : pages) {
JButton button = new JButton(page.label());
button.addActionListener(e -> show(page, content, cards, mounted));
sidebar.add(button);
}
JPanel root = new JPanel(new BorderLayout(12, 0));
root.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));
root.add(navigation, BorderLayout.WEST);
root.add(content, BorderLayout.CENTER);
show(pages.get(0), content, cards, mounted);
JFrame frame = new JFrame("Restaurant information");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(root);
frame.setMinimumSize(new Dimension(440, 240));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private static void show(Page page, JPanel content, CardLayout cards, Set<String> mounted) {
if (!mounted.contains(page.id())) {
content.add(page.create().get(), page.id());
mounted.add(page.id());
}
cards.show(content, page.id());
}
private static JPanel page(String title) {
JPanel panel = new JPanel(new BorderLayout(0, 8));
panel.setPreferredSize(new Dimension(460, 260));
JPanel form = new JPanel(new BorderLayout(0, 8));
form.add(new JLabel(title), BorderLayout.NORTH);
form.add(new JTextField(18), BorderLayout.CENTER);
panel.add(form, BorderLayout.NORTH);
return panel;
}
}
Add the following page to the List.of(...) call. The loop adds the menu button alongside the others. Give the page a unique ID, then click About to create and register its panel.
1
new Page("about", "About", () -> page("About this application"))
For two simple screens, creating both panels at startup is enough. A factory helps when a panel has setup work that can wait until its first visit or when a route registry already exists. If users need multiple independent detail panels, the cache needs a key for each instance. RSIS displays one restaurant detail at a time, so the same view can receive different IDs.
Figure 1. I opened Explore, Recommendations, and Settings in the same window. Watch the panels change to the right of the sidebar.
Check the center panel at smaller window sizes
On a narrow or short viewport, Explore reduces vertical gaps and card padding. If the content still exceeds the available height, the center panel scrolls. This layout logic belongs to Explore. The shared frame still places the sidebar and gives the active panel the remaining space. Compact Explore layout
Run ./gradlew exploreGallery in RSIS to render explore-light.png and explore-compact-1024.png under build/screen-gallery. Compare the placement of the filters and list in both images. In the running app, open Explore, Recommendations, and Settings from the sidebar while watching the surrounding window. The router test also exercises the lifecycle order and a return from a detail route. Router test
1
./gradlew test --tests org.example.rsis.ui.navigation.CardLayoutRouterTest
Figure 2. At the wider size, Explore shows the results and preview side by side below the filters.
Figure 3. At 1024×680, Explore uses less padding. This capture has the Haeundae district filter selected.
Before adding another screen
- Give the card a unique key and let the frame manage the window close action.
- Register and display cards on the EDT. Run database and network work on a worker thread.
- Stop the screen’s timers and close its subscriptions when you navigate away.
- Check keyboard and mouse access to the main controls at the minimum window size.