java - 匿名类,还是观察者模型中的一个 ActionEvent?
问题描述
考虑一个带有两个按钮的 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 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()
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
});
}
}
我应该选择一种方法而不是另一种方法的原因是什么?
解决方案
推荐阅读
- sed - sed - 在重复的字符串周围添加标签
- csv - 来自csv的gnuplot双图表
- javascript - spyOn 不模拟方法
- node.js - 如何在io.use中使用passportSocketIo和socketioJwt
- python - 如何将项目添加到映射到python中每个字典键的numpy数组?
- python - 无法在 Jupyter 笔记本中安装 pyspark
- python - python:在地图函数内产生
- typescript - 为什么闭包会在打字稿中忽略类型保护?
- pyspark - 将数据框写入 SQL 数据库而不替换表格式
- bash - bash中的间接左值引用