我研究了一些堆栈溢出问题,发现了类似的问题。
据我所知,在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
,以执行相同的操作。
阅读Swing教程中关于如何使用Action的部分,了解在ActionListener上使用Action的好处。