When to use EventListenerList instead of a general collection of listeners

前端 未结 3 1930
谎友^
谎友^ 2021-02-19 15:52

When I learned how to fire events in Java, I became familiar with EventListenerList. When I create my own listeners, I write the listener so it extends EventListener, I store th

3条回答
  •  粉色の甜心
    2021-02-19 16:05

    EventListenerList has a method, getListeners(Class t), specifically for the case where you are only interested in one event type.

    Here's an example of how to use it:

    protected void fireChangeOccurred(Change change) {
        for (ChangeListener listener:
             listenerList.getListeners(ChangeListener.class)) {
                listener.stateChanged(new ChangeEvent(this));
        }
    }
    

    If you choose to maintain your own collection of listeners, I recommend a CopyOnWriteArrayList.

提交回复
热议问题