How do I change JPanel inside a JFrame on the fly?

yanchenko picture yanchenko · Oct 20, 2008 · Viewed 148.8k times · Source

To put it simple, there's a simple java swing app that consists of JFrame with some components in it. One of the components is a JPanel that is meant to be replaced by another JPanel on user action.

So, what's the correct way of doing such a thing? I've tried

panel = new CustomJPanelWithComponentsOnIt();
parentFrameJPanelBelongsTo.pack();

but this won't work. What would you suggest?

Answer

Swapnonil Mukherjee picture Swapnonil Mukherjee · Oct 20, 2008

Your use case, seems perfect for CardLayout.

In card layout you can add multiple panels in the same place, but then show or hide, one panel at a time.