4

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.

RNJ
  • 15,272
  • 18
  • 86
  • 131
djmordigal
  • 549
  • 1
  • 5
  • 16

4 Answers4

4

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.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
2

You could use a TabbedPane, hide the tabs and switch them programatically from your application.

That way (for example for testing purposes) you could easily enable the tabs and check state of each of them at any moment.

But yeah, CardLayout is (in general) the good way to go.

You may be tempted to manually add and remove panels to a JFrame. I would advise against it - you may encouter some rendering issues and your code will get more complex. Besides, since you already have dedicated classes to do it, you should use them instead of reinventing the wheel.

Dariusz
  • 21,561
  • 9
  • 74
  • 114
0

I would personally remove all components of a JFrame. Something like that:

myFrame.getContentPane().removeAll();

And then add a completely new content pane, and then repaint and revalidate the frame.

mael
  • 2,214
  • 1
  • 19
  • 20
0

Design every screen as one JPanel (Add screen components to JPanel). When you know wich screen is required use JFrame.setContentPane(Container contentPane). This will replace everyting in JFrame except menu. If you need some parts of page remain same you have to use layout on contentPane and set screen only to one part of layout (depends on layout, see layot details here )

Piro
  • 1,367
  • 2
  • 19
  • 40