I it possible to implement an ActionListener to a global or local variable so that if variable changes the Listener performed a certain function / method etc..

I am working on a GUI application i am guessing there has to be a better solution than wrapping my main code in a forever loop is there ?

6 Years
Discussion Span
Last Post by hfx642

There's really only one way to do this right in Java, and that's to use a Listener, just like Swing does everywhere. Only snag is you have to implement it yourself, which is a bit tedious the first time (learning curve) but easy thereafter. You can use the existing ChangeListener interface to save some work, so it comes down to:
In the data class where the variable is:
. have a public method to add a ChangeListener, save the ChangeListener
. as part of the variable's "set" method, call the ChangeListener's stateChanged method
In the GUI/listener
. implement the stateChanged method - do what you want with the new value
. add (this) to the data class by calling its addChangeListener

Have a try, and come back here if you get stuck.


Observable certainly does give you a complete implementation of the Listener pattern. Unfortunately it runs into the Java single-inheritance problem, ie if you extend Observable you can't extend anything else, which will frequently be a problem.
IMHO the best way to use Observable is via composition rather than inheritance, ie create a private instance of Observable in your class, then write one-line covers for the public methods that simply delegate the call to the corresponding method in your Observable. At this point it's a close call as to whether or not you are better off doing that or just implementing the functionality yourself.
I would not recommend using the code in Observable as an example or code template. The code goes back to Java 1.0 and uses a pre 1.5 non-generic Vector, which it copies to an Object array in a synchronised block... it works, yes, but it's not how anyone would do it since Java 1.5.

Edited by JamesCherrill: n/a


Well... A listener doesn't go on a variable.
Put a listener on anything that changes your variable.
Variables don't change on there own.
Something has to change it.

Edited by hfx642: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.