0

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Cherple
  • 725
  • 3
  • 10
  • 24
  • *How do i tell code such that my action listener will be able to know exactly which jtextfield is triggering this action?* - if each text field invoked a different action, then you should be creating unique ActionListeners for each text field. Code with nested if/else statements in the listener should be avoided. – camickr Apr 28 '20 at 04:17

1 Answers1

2

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