我经历了一些堆栈溢出问题,发现了这个类似的问题。
据我了解,在此上下文的 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);
}
}