How to create multiple screens on the same window?

java, jframe, jpanel, swing

Solution

Yes, Cardlayout can be used to switch out `"Cards"`, i.e. different panels that are visible on the screen.

You can also switch `JPanels` directly with

jframe.getContentPane().remove(...); // Remove old panel from layout
jframe.getContentPane().add(...);
jframe.validate();
jframe.repaint()

Keep in mind that different Layouts work differently, so there's no single solution that works every time. Go through the documentation for different LayoutManagers to see how they work.

Problem

What I mean is, how to you design a user interface in which the screen changes with some action but the program operates entirely on one window? In other words, I suppose it'd be the same concept as navigating a website, for instance, in which everything happens on the same window (the web browser) but the screen contents change with every action (button click, link click, etc). I looked at the Java API and found the `CardLayout` class; am I heading in the right direction or is there a simpler way? (The page said `CardLayout` is somewhat complicated and recommended for those willing to manually code everything). I know there are the `validate()` and `repaint()` methods in `JFrame` but this might not be the right use for them. I'm not quite a beginner anymore but not extremely experienced yet either, so bear with me. Any guidance would be helpful. Thanks a lot.

Original source

Related problems