【问题标题】:CardLayout: How to show panels in one class in the ActionListeners in another class?CardLayout:如何在另一个类的 ActionListeners 中显示一个类中的面板?
【发布时间】:2014-05-03 22:12:48
【问题描述】:

我在JPanel 中添加了我的buttons(它有一个border layout,将按钮添加到它的south 位置),然后在(center 位置添加了another JPanel cardsPanel ) 父面板,并给它一个CardLayout我希望 cardsPanel 成为卡片的 container(我的意思是共享相同屏幕空间的面板)。

现在我需要做的是显示这些卡片(我正在调用将与卡片共享相同屏幕空间的面板)作为对父面板中按钮的响应。但是按钮位于父面板中,它们的动作监听器显然也位于那里。

所以问题是我如何showcardLayout.show())位于容器类(Cardlayout)中的面板作为对位于另一个类中的按钮的响应(BorderLayout ) ?


编辑 - 关于行动的问题:-

我希望发现实现ActionActionListener 更有用。 我还读到它们可以重复使用,并用于执行相同功能的按钮。我有几个按钮可以执行翻转特定卡片的功能(即在 CardLayout 中显示特定面板)。 我只编写了一个内部类,我想将它用于所有按钮。

所以我想将按钮标识符(当我们将按钮添加到其父级时用于标识按钮的字符串,例如 String btnIdentifier= "1"; panel.add(button1, btnIdentifier); )传递给此类的方法 actionPerformed(),即使我们从未显式调用 actionPerformed ()。 那么如何将按钮的字符串标识符传递给 actionPerformed() 方法,以便我可以对所有按钮使用相同的Action

最小代码:-

class Action extends AbstractAction{
            Action(String text, ImageIcon icon){
                super(text, icon);

            }
            public void actionPerformed(ActionEvent e) {
                button1.setBorderPainted(true);
                button1.setContentAreaFilled(true);
                if (btnIdentifier=="1"){  //////ASSUMING THAT BUTTON IDENTIFIER HAS SOMEHOW BEEN PASSED TO THIS METHOD
                    FirstCard firstCard= new FirstCard();
                    cardsPanel.add(firstCard, btnIdentifier);
                    cardLayout.show(cardsPanel, btnIdentifier);
                } else if (btnIdentifier=="2"){  //////ASSUMING THAT BUTTON IDENTIFIER HAS SOMEHOW BEEN PASSED TO THIS METHOD
                    SecondCard secondCard= new SecondCard();
                    cardsPanel.add(secondCard, btnIdentifier);
                    cardLayout.show(cardsPanel, btnIdentifier);
                } else if (btnIdentifier=="3"){  //////ASSUMING THAT BUTTON IDENTIFIER HAS SOMEHOW BEEN PASSED TO THIS METHOD
                    ThirdCard thirdCard= new ThirdCard();
                    cardsPanel.add(thirdCard, btnIdentifier);
                    cardLayout.show(cardsPanel, btnIdentifier);
                } 
            }
        }
        }

【问题讨论】:

    标签: java swing layout-manager cardlayout


    【解决方案1】:

    使用Action 封装所需的功能。使封闭面板的引用可见,如图herehere;或从具有(至少)package-private 访问权限的类中导出Action,如here 所示。

    【讨论】:

    • 另见 Card Layout Actions,引用 here
    • 我有一个关于Action 的后续问题,我已将其添加到我的问题中。如果你能回答,那就太好了。谢谢。
    • ActionEvent;使用getActionCommand() 了解命令名称并使用getSource() 确定哪个对象发送了消息。
    猜你喜欢
    • 2012-11-05
    • 1970-01-01
    • 2015-01-08
    • 2021-09-06
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多