java CardLayout 获取所选卡片的名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6505953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:07:56  来源:igfitidea点击:

CardLayout get the selected card's name

javaswingcardlayout

提问by wotan2009

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

如何在卡片布局中获取所选面板的字符串标识符。

回答by Fortega

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

CardLayout 不知道当前选择的面板是什么。在调用 show() 方法时,您应该自己将其保存在内存中。

回答by Pieter-Jan Van Robays

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

CardLayout 不允许您这样做。但是,您应该能够访问 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());