CardLayout get the selected card's name

我只是一个虾纸丫 提交于 2019-12-01 01:09:31

问题


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


回答1:


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




回答2:


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());


来源:https://stackoverflow.com/questions/6505953/cardlayout-get-the-selected-cards-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!