CardLayout get the name of the selected card

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

+4
source share
2 answers

CardLayout does not know what the selected panel is. You must store this in memory yourself when calling the show () method.

+10
source

CardLayout does not allow you to do this. However, you must have access to the top panel of CardLayout.

So, a little work is to give each added panel a name equal to a string identifier. This way you can get the top card and get its name. Here's 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()); 
+6
source

All Articles