Question

I'm having trouble figuring this one out.

The situation is no difficult to imagine so I hope I could post this without a sample code. I have JPanel with CardLayout. The panel contains several other panels as individual tabs. What I'm trying to achive is to create a JButton that will make the main panel show last opened tab (the one before the current was shown). No big deal I thought at first.

So I started by thinking how to get the current visible tab (panel) and found out that there is no native method for that in Panel or rather CardLayout that only contains methods first(), last(), next() and previous() which are no use to me.

Then I thought that maybe to achive my goal I might go through all components of the main panel and test which one is visible which would be the current one. I find it a little complicated, fine, but how do I make this panel show by CardLayout if I don't have its card name to call CardLayout method show(parent, name)?

At this point, I have no idea. I've been searching over the Internet but haven't found a solution, only that few people have been trying to figure something similar out. So I hope someone who already delt with this kind of issue comes across this topic :-)

Thanks for any suggestions.

Best regards

Martin S.

Was it helpful?

Solution

This brings up the question of how you arrived at the current card in the first place. If you used next() to get to the current card, then previous() will get you to the previous card and vice versa. If you use first() or last(), then you're out of luck.

Of course, you could always duplicate some of the information stored by the CardLayout to achieve your goal: if you maintain an array of component names (and update it whenever you call addLayoutComponent) as well as a previous index (and update this with next, previous and other calls), then you can just lookup the name of the previous component and use show to show the previous card.


Update: Since you know the tab names, here's how you can maintain the previous tab name:

String prevTab, curTab;

public void showTab(String newTab) {
  prevTab = curTab;
  curTab = newTab;
  layout.show(parent, curTab);
}

public void goBack() {
  layout.show(parent, prevTab);
}

OTHER TIPS

You can create a map object Map. And add panels & names to card layout and to the map. Afterwards, if you have the previously shown JPanel, you get its' name from map via map.get(JPanel p). And to find what JPanel was visible before the moment, you'll need to add ComponentListener to each JPanel. And make it to change some static variable on componentHidden event (e.g. static JPanel prev_shown).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top