• Post Reply Bookmark Topic Watch Topic
  • New Topic

actionListener and this

 
Chia-you Chai
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I have a question about the method actionPerformed(ActionEvent e);
In many times, we will specify the following statement :



But I have some confuse about that : We have already specify the object "button" itself, why we have to use "this" as the argument of the addActionListener() method ? Why we have to emphasize button and this to indicate button object itself?

Thank you for your reading and reply
 
Campbell Ritchie
Marshal
Posts: 52581
119
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In my opinion the correct answer is to avoid addActionListener(this) like the plague. This question came up yesterday, so look here first and see what we thought.

If there's anything you don't understand, ask again.
 
pete stein
Bartender
Posts: 1561
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"this" doesn't refer to the button, but rather it refers to the current class, and for this to work, the class must implement the ActionListener interface and in doing so, must have an actionPerformed(ActionEvent e) method. When the button is pressed, it will run the actionPerformed method of the ActionListener object that was loaded into it by this method.

Having said all this, I couldn't agree more with Campbell Ritchie's recommendation. Don't get in the habit of passing "this" as the ActionListener, but rather use specific ActionListener objects which can be anonymous inner class objects, private inner class objects, or standard class objects.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!