ActionListener 知道哪个组件触发了动作
ActionListener knowing which component triggered the action
我希望有一个动作监听器能够找出源代码,如下面的代码所示。我应该如何实施?
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 触发了这个动作?
ActionEvent#getSource()
returns 发起事件的对象(组件):
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
final Object source = event.getSource();
if (source.equals(tf1)) {
System.out.println("Textfield 1 updated");
}
else if (source.equals(tf2))
System.out.println("Textfield 2 updated");
}
}
};
我希望有一个动作监听器能够找出源代码,如下面的代码所示。我应该如何实施?
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 触发了这个动作?
ActionEvent#getSource()
returns 发起事件的对象(组件):
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
final Object source = event.getSource();
if (source.equals(tf1)) {
System.out.println("Textfield 1 updated");
}
else if (source.equals(tf2))
System.out.println("Textfield 2 updated");
}
}
};