【发布时间】:2020-08-11 19:01:05
【问题描述】:
我希望有一个 actionlistener 能够找出源代码,如下面的代码所示。我应该如何实现这个?
JTextField tf1 = new JTextField();
JTextField tf2 = new JTextField();
ActionListener listener = new ActionListener(){
@Override
public void actionPerformed(ActionEvent event){
if (source == tf1){//how to implement this?
System.out.println("Textfield 1 updated");
}
else if (source == tf2){//how to implement this?
System.out.println("Textfield 2 updated");
}
}
};
tf1.addActionListener(listener);
tf2.addActionListener(listener);
我如何告诉代码,以便我的动作侦听器能够准确地知道哪个 jtextfield 正在触发这个动作?
【问题讨论】:
-
我如何告诉代码,以便我的动作监听器能够准确地知道哪个 jtextfield 触发了这个动作? - 如果每个文本字段调用不同的动作,那么你应该为每个文本字段创建唯一的 ActionListener。应避免在侦听器中使用嵌套 if/else 语句的代码。
标签: java swing actionlistener jtextfield