galdikas
galdikas

Reputation: 1669

Accessing JButton that was clicked from ActionPerformed?

I have this assignment from college, and I have to have 5 buttons in the interface, and when button is clicked I have to perform action on that button. But when I use "this" in actionPerformed(), it doesn't refer to the "button that was clicked", and I can't workout what it actually refers to.

So:

  1. What does "this" refers to in ActionPerformed() action handler?
  2. Any nice way to do something with a button "that was clicked", without using a bunch of if statements, by using "e.getActionCommand()"?

Upvotes: 1

Views: 152

Answers (1)

FThompson
FThompson

Reputation: 28687

You can use EventObject#getSource(), which is inherited by ActionEvent.

@Override
public void actionPerformed(ActionEvent e) { 
    JButton source = (JButton) e.getSource();
    ...
}

Within an ActionListener, this refers to the ActionListener object itself, not the source object.

Upvotes: 6

Related Questions