• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

actionListener and this

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 1561
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic