【问题标题】:ActionListener knowing which component triggered the actionActionListener 知道哪个组件触发了动作
【发布时间】: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


【解决方案1】:

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");
    }
  }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多