5

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.

chimeracoder
  • 20,648
  • 21
  • 60
  • 60
  • Is that backend object written by you, ie. can you modify it? It won't fire any events unless it contains code that does it. – fish Nov 09 '10 at 08:13

3 Answers3

6

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:

Grodriguez
  • 21,501
  • 10
  • 63
  • 107
2

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);
         }
    }
}
Vijay Mathew
  • 26,737
  • 4
  • 62
  • 93
1

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.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • 1
    Thanks - but the object that I'm monitoring isn't actually a Swing component (it's running in the background in the main thread). – chimeracoder Nov 09 '10 at 05:17
  • 1
    @thebackhand, It doesn't have to be a Swing component. I gave you the wrong link to look at. You can use the PropertyChangeSupport class to help you register the listeners and fire the events – camickr Nov 09 '10 at 05:40