Firing events in Java when an object changes state

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

I know that Swing processes this template through Listeners - and I use Swing for this project, but I'm not sure what the listener would apply to this case. The user state is not changed by the user, and listeners seem to be triggered only by user actions.

Change The object that I control is not itself a Swing component - it works in the background in the main thread.

+4
source share
3 answers

Perhaps you should take a look at java.util.Observable , which is designed specifically for this purpose.

Here's the JavaWorld Observer and Observable tutorial:

+5
source

Whether this state is changed by the user or not, it does not matter. You can call listener callbacks from a method that changes state, and make sure that the state of an object can only be changed using this method:

class A { public void changeState(State newState) { state = newState; for (SomeEventListenerInterface el : listeners) { el.nofity(this, newState); } } } 
+2
source

and Listeners seem to be triggered only by user actions.

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

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

+1
source

Source: https://habr.com/ru/post/916410/


All Articles