ActionListener知道哪个组件触发了操作

问题描述 投票:0回答:1

我希望有一个动作侦听器,以便能够找出源,如下面的代码所示。我应该如何实施?

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触发了此动作?

java actionlistener jtextfield
1个回答
0
投票

ActionEvent#getSource()返回引发事件的对象(组件):

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");
    }
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.