8

How can I get the string identifier of the selected panel in card layout.

jzd
  • 23,473
  • 9
  • 54
  • 76
wotan2009
  • 151
  • 1
  • 3
  • 6

2 Answers2

14

The CardLayout does not know what the currently selected panel is. You should keep this in memory yourself, when calling the show() method.

Fortega
  • 19,463
  • 14
  • 75
  • 113
  • +1 Here's a related [example](http://stackoverflow.com/questions/6432170/how-to-change-ui-depending-on-combo-box-selection/6432291#6432291). – trashgod Jun 28 '11 at 15:36
  • that's ok. is it a feature we should ask to swing team? the fact that in java 7 they've released a new component for swing (the JLayer) suggests that oracle will at least keep swing in maintenance. so why not add useful features like this one? – AgostinoX Sep 27 '11 at 20:06
10

The CardLayout does not allow you to do this. However, you should be able to access the top panel of the CardLayout.

So a little work around is to give each added panel a name, equal to the string identifier. That way you can get the top card, and get it's name. This is how you do it:

final String CARD1 = "Card 1";
final String CARD2 = "Card 2";

JPanel panel = new JPanel(new CardLayout());
JPanel card1 = new JPanel();
card1.setName(CARD1);
JPanel card2 = new JPanel();
card2.setName(CARD2);

panel.add(card1);
panel.add(card2);

//now we want to get the String identifier of the top card:
JPanel card = null;
for (Component comp : panel.getComponents()) {
    if (comp.isVisible() == true) {
        card = (JPanel) comp;
    }
}
System.out.println(card.getName());
  • The notion of searching the top level JPanel for visible components (hopefully only one is visible) is the important part. Whether the panels have names or not is secondary. Once I have a handle to the current card panel, I can do all sorts of useful things – Fred Andrews Oct 14 '18 at 18:01