Search code examples
javaswingindexinglayout-managercardlayout

Card Layout get the current card string


i'm using cardlayout in application and want to get the name of the current active card i tried many methods but with no mean, for example this method seems to be no longer exists

panel.getLayout().getActiveItem()

also i tried this but it doesn't work too

 Panel card = null;
      for (Component comp : cardPanel.getComponents()) {
           if (comp.isVisible()) {
                System.out.println(card.getName());

                    }
                 }

for example: the following stamts adds several panels to a card layout, i want to return 1,2,3,4 or 5 of the currently active card:

    cardPanel.add(firstP, "1");
    cardPanel.add(secondP, "2");
    cardPanel.add(thirdP, "3");
    cardPanel.add(fourthP, "4");
    cardPanel.add(fifthP, "5");

what's the possible ways to do that?


Solution

  • CardLayout does not expose its own mapping between of components and its keys (here 1, 2, 3, 4...), so using the layout itself will not reveal how the "cards" are hashed.

    If you wish to use the getName method, remember that you must set this yourself first as the field is not set by default:

    firstPanel.setName("1");
    cardPanel.add(firstPanel, firstPanel.getName());
    

    then, using your for loop, you will be able to get the current card String.