问题描述
我研究了一些堆栈溢出问题,发现了 this 类似的问题。
据我了解,在此上下文的 actionPerformed 方法中使用 switch 语句将不起作用,并且需要 if-else 语句。
有没有更有效的方法来做到这一点而没有重复的代码?我听说我可以使用抽象操作为多个按钮提供相同的操作,但我还没有弄清楚如何正确使用它。
@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);
}
}
解决方法
据我了解,在此上下文的 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));
我听说我可以使用抽象操作为多个按钮提供相同的操作
您可以使用 Action
来提供独特的功能。 Action
的好处是它可以由不同的组件(例如 JButton
或 JMenuItem
)共享以执行相同的操作。
阅读有关 How to Use Action 的 Swing 教程中的部分,了解在 ActionListener 上使用 Action 的好处。