EventListenerList - why step by 2?

This is the example for how to fire events using EventListenerList as shown in the Sun javadoc - http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/event/EventListenerList.html

Why does the loop do in steps of 2, checking the type of one listener but calling the other?

protectedvoid fireFooXXX(){

// Guaranteed to return a non-null array

Object[] listeners = listenerList.getListenerList();

// Process the listeners last to first, notifying

// those that are interested in this event

for (int i = listeners.length-2; i>=0; i-=2){

if (listeners[i]==FooListener.class){

// Lazily create the event:

if (fooEvent ==null)

fooEvent =new FooEvent(this);

((FooListener)listeners[i+1]).fooXXX(fooEvent);

}

}

}

[1392 byte] By [thebobstera] at [2007-10-1 2:41:48]
# 1

>

> Why does the loop do in steps of 2, checking the type

> of one listener but calling the other?

It doesn't. When you add a listener to your EventListenerList you specify the class of the listener interface it implements. The class is stored with an even index in the listener list, and the listener itself is stored with an odd index. So the line if (listeners[i]==FooListener.class)

checks if the listener that is stored in listeners[i+1]

is a FooListener or not.

The reason it stores the class information explicitly, rather than just calling getClass() on the stored listener is illustrated by the following example:

class ActionAndMouseListenerImpl implements ActionListener, MouseListener {

....

}

...

...

ActionListener myListener = new ActionAndMouseListenerImpl();

JButton btn = new JButton("OK");

btn.addActionListener(myListener);

The implementation of EventListenerList makes sure that myListener won't be used as a MouseListener on the JButton, since we only added it as an ActionListener.

Hope this helps.

Torgila at 2007-7-8 12:21:49 > top of Java-index,Archived Forums,Java 2 Software Development Kit (J2SE SDK)...