java - 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);
}
}
解决方案
据我了解,在此上下文的 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 的好处。
推荐阅读
- google-chrome - 是否可以在 Chrome 应用程序中使用 Hola 等 VPN 扩展程序?
- node.js - Commander.js - 实现前一个完成时执行的子命令
- thymeleaf - Thymleaf I18N 语法
- python-xarray - 生成具有多维无维坐标的 xarray
- java - ThreadPoolExecutor.execute(Runnable command) 何时创建新线程
- flutter - 如何在颤动应用程序中将边框半径设置为底部应用程序栏?
- php - 从 url 获取语言
- c++ - 在编译时读取文件(constexpr 或其他)
- mysql - 保存很慢
- c++ - CreateGraphicsPipelineState 失败并显示 E_INVALIDARG