Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triggering events in Java when an object's state changes

I have an object in Java whose state changes over the course of time. When one of the fields in the object reaches a certain value, I want an external event to be triggered.

I know Swing handles this pattern through Listeners - and I am using Swing for this project - but I'm not sure what kind of Listener would apply to this case. The object's state is not being changed by the user, and Listeners seem to be triggered only by users' actions.

Edit: The object that I'm monitoring isn't itself a Swing component - it runs in the background in the main thread.

like image 942
chimeracoder Avatar asked Nov 09 '10 05:11

chimeracoder


3 Answers

You might want to have a look at java.util.Observable, which is designed just for this purpose.

Here's a JavaWorld tutorial on Observer and Observable:

  • http://www.javaworld.com/javaworld/jw-10-1996/jw-10-howto.html
like image 161
Grodriguez Avatar answered Sep 24 '22 09:09

Grodriguez


Whether that state is changed by the user or not really do not matter. You can invoke the listener callbacks from the method that changes the state and make sure that the state of the object could be changed only through that method:

class A {
    public void changeState(State newState) {
         state = newState;
         for (SomeEventListenerInterface el : listeners) {
              el.nofity(this, newState);
         }
    }
}
like image 20
Vijay Mathew Avatar answered Sep 22 '22 09:09

Vijay Mathew


and Listeners seem to be triggered only by users' actions.

Not always. For example when you change the property of many Swing components (background, font, etc) a PropertyChangeEvent is fired.

I would suggest you can also use this event. Read the section from the Swing tutorial on How to Write a Property Change Listener for an example.

like image 21
camickr Avatar answered Sep 23 '22 09:09

camickr