Win a copy of Micro Frontends in Action this week in the Server-Side JavaScript and NodeJS forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

actionListener and this

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
Posts: 70378
  • 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.
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.
If you look closely at this tiny ad, you will see five bicycles and a naked woman:
the value of filler advertising in 2020
    Bookmark Topic Watch Topic
  • New Topic