What is the common way to program action listeners?

Posted by Roman on Stack Overflow See other posts from Stack Overflow or by Roman
Published on 2010-03-12T16:55:39Z Indexed on 2010/03/12 16:57 UTC
Read the original article Hit count: 163

Filed under:
|

I just started to learn how to use action listeners. To my understanding it works in the following way:

  1. There are some classes which contains "addActionListener" method by default (for example classes for buttons).

  2. Using this method we add an action listener to an object. For example: listenedObject.addActionListener(listeningObject).

  3. When an action with the "listenedObject" is performed, the "actionPerformed" method of the "listeningObject" will be called. So, it means that when we program a class for the listeningObject, we need to put there "actionPerformed" method.

What is not clear to me, should we create a new class for every object that we want to listen. It does not seem to me as an elegant solution. On the other hand, if we have one action listener class for all (or at least many) object, than we have a problem since a instance of this class will not know which object is calling the "actionPerformed" method (and we need to know that since actions performed by the actionPerformed differs depending on who is called for this method).

In my opinion, for every listened object we need to create are "personal" action listener and we can do it by setting a specific value to the corresponding field of the action listener. But I am not sure that it is a standard way to go? How do usually people do it?

© Stack Overflow or respective owner

Related posts about java

Related posts about actionlistener