Swing: event listener support class

Is there any existing class that helps support EventListener add / remove operations? (like PropertyChangeSupport)

I am trying to break my code into a model and look at Java. I have some data that comes randomly and would like the model to support some kind of EventListener so that the view can subscribe to changes to the model. The data is plentiful and complex that I don’t want to do all the small-scale support for modifying Javabeans properties; rather, I just wanted to warn that the model has changed roughly.

How can i do this?

+6
java listener swing
source share
2 answers

I would handle this with ChangeEvent . This is just an indication that something has changed.

How to implement add / remove / fire functionality. A mechanism like PropertyChangeSupport does not exist, but the code is quite simple, and this is not necessary.

private final EventListenerList listenerList = new EventListenerList(); private final ChangeEvent stateChangeEvent = new ChangeEvent(this); public void addChangeListener(ChangeListener l) { listenerList.add(ChangeListener.class, l); } public void removeChangeListener(ChangeListener l) { listenerList.remove(ChangeListener.class, l); } protected void fireChange() { for (ChangeListener l: listenerList.getListeners(ChangeListener.class)) { l.stateChanged(stateChangeEvent); } } 

Note. JComponent provides a protected listenerList object for use by subclasses.

+9
source share

I'm not sure if this answers your question, but you can use javax.swing.event.EventListenerList , it supports add () and remove () operations for your listeners. Then you can iterate over a separate listener subclass to fire events:

 for (MyListener listener : listenerList.getListeners(MyListener.class) { listener.fireEvent(...); } 
+1
source share

All Articles