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.
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:
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);
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With