[英]Which is better for multiple actions in a class? Anonymous inner classes or if statements in actionPerformed()?
I am working on making menus in a java JFrame. 我正在制作Java JFrame中的菜单。 I've seen two ways of having different responses to different events in the same class. 我已经看到了两种在同一班上对不同事件做出不同反应的方式。 One is to use anonymous inner classes as described in this answer from a few years ago: https://stackoverflow.com/a/10472395/5960074 一种是使用几年前此答案中所述的匿名内部类: https : //stackoverflow.com/a/10472395/5960074
public static void createMenuBar()
{
//Main Menu Items
menubar.add(fileMenu);
MainWindow.window.setJMenuBar(menubar);
//Sub menu items
saveItem = new JMenuItem("Save");
loadItem = new JMenuItem("Load");
//Add to the "File" menu item
fileMenu.add(saveItem);
fileMenu.add(loadItem);
//Anonymous Inner classes for actionListeners
//Action event for saving
saveItem.addActionListener(new ActionListener(){ //adding the listener
@Override
public void actionPerformed(ActionEvent e){ //creating the specific action for save
System.out.println("You tried to save.");
}
});
}
In my code it looks like this and it works (as in at this point it prints "You tried to save." to the console). 在我的代码中,它看起来像这样并且可以正常工作(因为此时它在控制台上显示“您试图保存。”)。
I've seen other people implement ActionListener in the class and then in the method actionPerformed() they use if statements that track the source of the event. 我见过其他人在类中实现ActionListener,然后在他们使用ifPer语句跟踪事件源的方法actionPerformed()中。 So there is one event but the code changes on what triggers it. 因此,只有一个事件,但是代码在触发它的原因上发生了变化。
The first method seems messy and the second easier to read. 第一种方法看起来很凌乱,第二种方法更易于阅读。 Is there a reason to do the first method over the second? 有理由在第二种方法中采用第一种方法吗?
Thanks. 谢谢。
First, avoid using static
, you really (really) don't need it, it promotes bad code design. 首先,避免使用static
,您真的(真的)不需要它,它会导致代码设计不良。
Assuming you use Java 8, and thus can use lambda's: 假设您使用Java 8,因此可以使用lambda:
public void createMenuBar() {
...
saveItem.addActionListener(this::save);
loadItem.addActionListener(this::load);
}
private save(ActionEvent e) {
....
}
private load(ActionEvent e) {
....
}
If you cannot use lambdas using inner classes is better than implementing the interface and using if
statements. 如果您不能使用lambda,则使用内部类比实现接口和使用if
语句更好。
public class MyGui {
private class SaveAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
....
}
}
private class LoadAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
....
}
}
public void createMenuBar() {
...
saveItem.addActionListener(new SaveAction());
loadItem.addActionListener(new LoadAction());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.