KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javax > swing > event > EventListenerList


1 /*
2  * @(#)EventListenerList.java 1.36 04/05/05
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7 package javax.swing.event;
8
9 import java.io.*;
10 import java.util.*;
11 import java.lang.reflect.Array JavaDoc;
12
13 /**
14  * A class that holds a list of EventListeners. A single instance
15  * can be used to hold all listeners (of all types) for the instance
16  * using the list. It is the responsiblity of the class using the
17  * EventListenerList to provide type-safe API (preferably conforming
18  * to the JavaBeans spec) and methods which dispatch event notification
19  * methods to appropriate Event Listeners on the list.
20  *
21  * The main benefits that this class provides are that it is relatively
22  * cheap in the case of no listeners, and it provides serialization for
23  * event-listener lists in a single place, as well as a degree of MT safety
24  * (when used correctly).
25  *
26  * Usage example:
27  * Say one is defining a class that sends out FooEvents, and one wants
28  * to allow users of the class to register FooListeners and receive
29  * notification when FooEvents occur. The following should be added
30  * to the class definition:
31  * <pre>
32  * EventListenerList listenerList = new EventListenerList();
33  * FooEvent fooEvent = null;
34  *
35  * public void addFooListener(FooListener l) {
36  * listenerList.add(FooListener.class, l);
37  * }
38  *
39  * public void removeFooListener(FooListener l) {
40  * listenerList.remove(FooListener.class, l);
41  * }
42  *
43  *
44  * // Notify all listeners that have registered interest for
45  * // notification on this event type. The event instance
46  * // is lazily created using the parameters passed into
47  * // the fire method.
48  *
49  * protected void fireFooXXX() {
50  * // Guaranteed to return a non-null array
51  * Object[] listeners = listenerList.getListenerList();
52  * // Process the listeners last to first, notifying
53  * // those that are interested in this event
54  * for (int i = listeners.length-2; i>=0; i-=2) {
55  * if (listeners[i]==FooListener.class) {
56  * // Lazily create the event:
57  * if (fooEvent == null)
58  * fooEvent = new FooEvent(this);
59  * ((FooListener)listeners[i+1]).fooXXX(fooEvent);
60  * }
61  * }
62  * }
63  * </pre>
64  * foo should be changed to the appropriate name, and fireFooXxx to the
65  * appropriate method name. One fire method should exist for each
66  * notification method in the FooListener interface.
67  * <p>
68  * <strong>Warning:</strong>
69  * Serialized objects of this class will not be compatible with
70  * future Swing releases. The current serialization support is
71  * appropriate for short term storage or RMI between applications running
72  * the same version of Swing. As of 1.4, support for long term storage
73  * of all JavaBeans<sup><font size="-2">TM</font></sup>
74  * has been added to the <code>java.beans</code> package.
75  * Please see {@link java.beans.XMLEncoder}.
76  *
77  * @version 1.36 05/05/04
78  * @author Georges Saab
79  * @author Hans Muller
80  * @author James Gosling
81  */

82 public class EventListenerList implements Serializable {
83     /* A null array to be shared by all empty listener lists*/
84     private final static Object JavaDoc[] NULL_ARRAY = new Object JavaDoc[0];
85     /* The list of ListenerType - Listener pairs */
86     protected transient Object JavaDoc[] listenerList = NULL_ARRAY;
87
88     /**
89      * Passes back the event listener list as an array
90      * of ListenerType-listener pairs. Note that for
91      * performance reasons, this implementation passes back
92      * the actual data structure in which the listener data
93      * is stored internally!
94      * This method is guaranteed to pass back a non-null
95      * array, so that no null-checking is required in
96      * fire methods. A zero-length array of Object should
97      * be returned if there are currently no listeners.
98      *
99      * WARNING!!! Absolutely NO modification of
100      * the data contained in this array should be made -- if
101      * any such manipulation is necessary, it should be done
102      * on a copy of the array returned rather than the array
103      * itself.
104      */

105     public Object JavaDoc[] getListenerList() {
106     return listenerList;
107     }
108
109     /**
110      * Return an array of all the listeners of the given type.
111      * @return all of the listeners of the specified type.
112      * @exception ClassCastException if the supplied class
113      * is not assignable to EventListener
114      *
115      * @since 1.3
116      */

117     public <T extends EventListener> T[] getListeners(Class JavaDoc<T> t) {
118     Object JavaDoc[] lList = listenerList;
119     int n = getListenerCount(lList, t);
120         T[] result = (T[])Array.newInstance(t, n);
121     int j = 0;
122     for (int i = lList.length-2; i>=0; i-=2) {
123         if (lList[i] == t) {
124         result[j++] = (T)lList[i+1];
125         }
126     }
127     return result;
128     }
129
130     /**
131      * Returns the total number of listeners for this listener list.
132      */

133     public int getListenerCount() {
134     return listenerList.length/2;
135     }
136
137     /**
138      * Returns the total number of listeners of the supplied type
139      * for this listener list.
140      */

141     public int getListenerCount(Class JavaDoc<?> t) {
142     Object JavaDoc[] lList = listenerList;
143         return getListenerCount(lList, t);
144     }
145
146     private int getListenerCount(Object JavaDoc[] list, Class JavaDoc t) {
147         int count = 0;
148     for (int i = 0; i < list.length; i+=2) {
149         if (t == (Class JavaDoc)list[i])
150         count++;
151     }
152     return count;
153     }
154
155     /**
156      * Adds the listener as a listener of the specified type.
157      * @param t the type of the listener to be added
158      * @param l the listener to be added
159      */

160     public synchronized <T extends EventListener> void add(Class JavaDoc<T> t, T l) {
161     if (l==null) {
162         // In an ideal world, we would do an assertion here
163
// to help developers know they are probably doing
164
// something wrong
165
return;
166     }
167     if (!t.isInstance(l)) {
168         throw new IllegalArgumentException JavaDoc("Listener " + l +
169                      " is not of type " + t);
170     }
171     if (listenerList == NULL_ARRAY) {
172         // if this is the first listener added,
173
// initialize the lists
174
listenerList = new Object JavaDoc[] { t, l };
175     } else {
176         // Otherwise copy the array and add the new listener
177
int i = listenerList.length;
178         Object JavaDoc[] tmp = new Object JavaDoc[i+2];
179         System.arraycopy(listenerList, 0, tmp, 0, i);
180
181         tmp[i] = t;
182         tmp[i+1] = l;
183
184         listenerList = tmp;
185     }
186     }
187
188     /**
189      * Removes the listener as a listener of the specified type.
190      * @param t the type of the listener to be removed
191      * @param l the listener to be removed
192      */

193     public synchronized <T extends EventListener> void remove(Class JavaDoc<T> t, T l) {
194     if (l ==null) {
195         // In an ideal world, we would do an assertion here
196
// to help developers know they are probably doing
197
// something wrong
198
return;
199     }
200     if (!t.isInstance(l)) {
201         throw new IllegalArgumentException JavaDoc("Listener " + l +
202                      " is not of type " + t);
203     }
204     // Is l on the list?
205
int index = -1;
206     for (int i = listenerList.length-2; i>=0; i-=2) {
207         if ((listenerList[i]==t) && (listenerList[i+1].equals(l) == true)) {
208         index = i;
209         break;
210         }
211     }
212     
213     // If so, remove it
214
if (index != -1) {
215         Object JavaDoc[] tmp = new Object JavaDoc[listenerList.length-2];
216         // Copy the list up to index
217
System.arraycopy(listenerList, 0, tmp, 0, index);
218         // Copy from two past the index, up to
219
// the end of tmp (which is two elements
220
// shorter than the old list)
221
if (index < tmp.length)
222         System.arraycopy(listenerList, index+2, tmp, index,
223                  tmp.length - index);
224         // set the listener array to the new array or null
225
listenerList = (tmp.length == 0) ? NULL_ARRAY : tmp;
226         }
227     }
228
229     // Serialization support.
230
private void writeObject(ObjectOutputStream s) throws IOException {
231     Object JavaDoc[] lList = listenerList;
232     s.defaultWriteObject();
233     
234     // Save the non-null event listeners:
235
for (int i = 0; i < lList.length; i+=2) {
236         Class JavaDoc t = (Class JavaDoc)lList[i];
237         EventListener l = (EventListener)lList[i+1];
238         if ((l!=null) && (l instanceof Serializable)) {
239         s.writeObject(t.getName());
240         s.writeObject(l);
241         }
242     }
243     
244     s.writeObject(null);
245     }
246
247     private void readObject(ObjectInputStream s)
248     throws IOException, ClassNotFoundException JavaDoc {
249         listenerList = NULL_ARRAY;
250     s.defaultReadObject();
251     Object JavaDoc listenerTypeOrNull;
252     
253     while (null != (listenerTypeOrNull = s.readObject())) {
254             ClassLoader JavaDoc cl = Thread.currentThread().getContextClassLoader();
255         EventListener l = (EventListener)s.readObject();
256         add((Class JavaDoc<EventListener>)Class.forName((String JavaDoc)listenerTypeOrNull, true, cl), l);
257     }
258     }
259
260     /**
261      * Returns a string representation of the EventListenerList.
262      */

263     public String JavaDoc toString() {
264     Object JavaDoc[] lList = listenerList;
265     String JavaDoc s = "EventListenerList: ";
266     s += lList.length/2 + " listeners: ";
267     for (int i = 0 ; i <= lList.length-2 ; i+=2) {
268         s += " type " + ((Class JavaDoc)lList[i]).getName();
269         s += " listener " + lList[i+1];
270     }
271     return s;
272     }
273 }
274
Popular Tags