Skip to content
Advertisement

ActionListener knowing which component triggered the action

I would like to have an actionlistener to be able to figure out the source as shown in the code below. How should i implement this?

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

How do i tell code such that my action listener will be able to know exactly which jtextfield is triggering this action?

Advertisement

Answer

ActionEvent#getSource() returns the object (component) that originated the event:

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");
    }
  }
};
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement