Java 匿名类,还是观察者模型中的一个ActionEvent?
考虑一个带有两个按钮的JFrame: 设置1: 一个actionPerformed方法被传递给子对象,其处理方式基于传递事件的对象的IDJava 匿名类,还是观察者模型中的一个ActionEvent?,java,swing,event-handling,observer-pattern,anonymous-class,Java,Swing,Event Handling,Observer Pattern,Anonymous Class,考虑一个带有两个按钮的JFrame: 设置1: 一个actionPerformed方法被传递给子对象,其处理方式基于传递事件的对象的ID import javx.swing.JFrame; import javax.swing.JLabel; import javax.swing.JButton; public class View extends JFrame implements ActionListener{ private JButton btn1; private J
import javx.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
public class View extends JFrame implements ActionListener{
private JButton btn1;
private JButton btn2;
private JLabel lbl;
public View(){
btn1 = new JButton("hi");
btn2 = new JButton("bye");
setLayout(new GridBagLayout());
GridBagConstraings gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 0;
gc.weightx = 1;
gc.weighty = 1;
add(btn1,gc);
gc.gridx = 1;
gc.gridy = 0;
gc.weightx = 1;
gc.weighty = 1;
add(btn2,gc);
btn1.addActionListener(this);
btn2.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e){
JButton src = (JButton)e.getSource();
if(src == btn1){
//do this
}else{
//do that
}
}
}
设置2:
每个模块都会被传递一个匿名类的实例,该类包含自己独特的actionPerformed()
我应该选择一种方法而不是另一种方法的原因是什么?为每个按钮分别设置事件处理程序对象。您可以从事件处理程序中的某些回调调用公共方法。这样,您将避免使用if-else检查事件发生的按钮。另外,如果添加了新按钮或删除了按钮,那么从代码可维护性的角度来看,生活会更轻松。注意,自Java 8以来,您可以通过lambda表达式或方法引用实现
ActionListener
,例如btn1.addActionListener(事件->系统.out.println(“hello”)代码>,btn1.addActionListener(事件->JOptionPane.showMessageDialog(这是“你好”)代码>,btn2.addActionListener(事件->处置())代码>,或btn2.addActionListener(ev->System.exit(0))
,这是一个更合理的理由,不能混合不同的操作。
import javx.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
public class View extends JFrame{
private JButton btn1;
private JButton btn2;
private JLabel lbl;
public View(){
btn1 = new JButton("hi");
btn2 = new JButton("bye");
setLayout(new GridBagLayout());
GridBagConstraings gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 0;
gc.weightx = 1;
gc.weighty = 1;
add(btn1,gc);
gc.gridx = 1;
gc.gridy = 0;
gc.weightx = 1;
gc.weighty = 1;
add(btn2,gc);
btn1.addActionListener(new ActionListener(){
//do this
});
btn2.addActionListener(new ActionListener(){
//do that
});
}
}