Hi,

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 ?

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.

Look at the Observable class. It might provide some help for you problem.

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.

Member Avatar for hfx642

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.