views:

63

answers:

2

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

I'm trying to partition my code into a model and view in Java. I have some data that arrives erratically, and would like the model to support some kind of EventListener so that a view can subscribe to changes in the model. The data is numerous + complicated enough that I don't want to have to do the whole fine-grained Javabeans property change support; rather I would just like to allow notification that the model has changed in a coarse way.

how can I best do this?

+1  A: 

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

for (MyListener listener : listenerList.getListeners(MyListener.class) {
   listener.fireEvent(...);
}
Guillaume
+3  A: 

I would handle that with a ChangeEvent. It's just an indication that something has changed.

As for implementing the add/remove/fire functionality. There is no mechanism like PropertyChangeSupport, but the code is simple enough there's not really a need for it.

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 sub-classes.

Devon_C_Miller
great, thanks!.
Jason S
Yeah, `ChangeEvent` is the one true state change event. `PropertyChangeEvent` is just wrong, and IIRC incorrectly implemented throughout Swing. It's probably too much to move to an event model that doesn't have that pointless event object. :( (Oh, and @Devon, the odd `final` wouldn't go a miss there.)
Tom Hawtin - tackline
@Tom thanks for the catch.
Devon_C_Miller