首页 > 解决方案 > Switch Case In ActionPerformed?

问题描述

我经历了一些堆栈溢出问题,发现了这个类似的问题。

据我了解,在此上下文的 actionPerformed 方法中使用 switch 语句将不起作用,并且需要 if-else 语句。

有没有更有效的方法来做到这一点而无需重复代码?我听说我可以使用 Abstract Action 为多个按钮提供相同的操作,但我还没有弄清楚如何正确使用它。

@Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == loginButton){
            cardLayout.show(cards, LOGIN_PANEL);
        }
        else if(e.getSource() == signUpButton){
            cardLayout.show(cards, SIGN_UP_PANEL);
        }
        else if(e.getSource() == transactionHistoryButton){
            cardLayout.show(cards,TABLE_PANEL);
        }
        else if(e.getSource() == depositButton){
            cardLayout.show(cards, DEPOSIT_PANEL);
        }
        else if(e.getSource() == withdrawButton){
            cardLayout.show(cards, WITHDRAW_PANEL);
        }
        else if(e.getSource() == checkBalanceButton){
            cardLayout.show(cards,BALANCE_PANEL);
        }
        else if(e.getSource() == logout){
            cardLayout.show(cards, OPTION_PANEL);
        }
        else if(e.getSource() == backButtonP1){
            cardLayout.show(cards, OPTION_PANEL);
        }
        else if(e.getSource() == backButtonP2){
            cardLayout.show(cards, OPTION_PANEL);
        }
        else if(e.getSource() == backButtonP3){
            cardLayout.show(cards, UNLOCKED_PANEL);
        }
        else if(e.getSource() == backButtonP4){
            cardLayout.show(cards, UNLOCKED_PANEL);
        }
        else if(e.getSource() == backButtonP5){
            cardLayout.show(cards, UNLOCKED_PANEL);
        }
        else if(e.getSource() == backButtonP6){
            cardLayout.show(cards, UNLOCKED_PANEL);
        }
    }

标签: javaif-statementswitch-statementcardlayoutabstract-action

解决方案


据我了解,在此上下文的 actionPerformed 方法中使用 switch 语句将不起作用,并且需要 if-else 语句。

不要尝试使用 switch 语句或嵌套的 if/else 语句。这表明设计不佳。

有没有更有效的方法来做到这一点而无需重复代码?

如果您想ActionListener为所有按钮共享相同的内容,那么您需要编写一个通用的ActionListener.

就像是:

ActionListener al = new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        String command = e.getActionCommand();
        cardLayout.show(cards, command)
    }
}

然后,当您创建按钮时,您将使用:

JButton loginButton = new JButton("Login");
loginButton.setActionCommand(LOGIN_PANEL);
loginButton.addActionListener( al );

或者,您可以使用 Java lambda 轻松ActionListener为每个按钮创建一个唯一的。就像是:

loginButton.addActionListener((e) -> cardLayout.show(cards, LOGIN_PANEL));

我听说我可以使用 Abstract Action 为多个按钮提供相同的操作

您将使用Action, 来提供独特的功能。an 的好处Action是它可以被不同的组件共享,例如 JButton或 a JMenuItem,以执行相同的操作。

阅读 Swing 教程中有关如何使用 Action的部分,了解使用 Action 而非 ActionListener 的好处。


推荐阅读