View Javadoc

1   /*
2    * Copyright (c) 2005, the JUNG Project and the Regents of the University of
3    * California All rights reserved.
4    *
5    * This software is open-source under the BSD license; see either "license.txt"
6    * or http://jung.sourceforge.net/license.txt for a description.
7    *
8    * Created on Aug 18, 2005
9    */
10  
11  package edu.uci.ics.jung.visualization.util;
12  
13  import javax.swing.event.ChangeEvent;
14  import javax.swing.event.ChangeListener;
15  import javax.swing.event.EventListenerList;
16  
17  /**
18   * Basic implementation of ChangeEventSupport, using
19   * standard jdk classes
20   * 
21   * @author Tom Nelson - tomnelson@dev.java.net
22   *
23   */
24  public class DefaultChangeEventSupport implements ChangeEventSupport {
25      
26      Object eventSource;
27      /**
28       * holds the registered listeners
29       */
30      protected EventListenerList listenerList = new EventListenerList();
31  
32      /**
33       * Only one <code>ChangeEvent</code> is needed
34       * instance since the
35       * event's only state is the source property.  The source of events
36       * generated is always "this".
37       */
38      protected transient ChangeEvent changeEvent;
39      
40      public DefaultChangeEventSupport(Object eventSource) {
41          this.eventSource = eventSource;
42      }
43  
44      public void addChangeListener(ChangeListener l) {
45          listenerList.add(ChangeListener.class, l);
46      }
47      
48      public void removeChangeListener(ChangeListener l) {
49          listenerList.remove(ChangeListener.class, l);
50      }
51      
52      public ChangeListener[] getChangeListeners() {
53          return listenerList.getListeners(ChangeListener.class);
54      }
55  
56      /**
57       * Notifies all listeners that have registered interest for
58       * notification on this event type.  The event instance 
59       * is lazily created.
60       * The primary listeners will be views that need to be repainted
61       * because of changes in this model instance
62       * @see EventListenerList
63       */
64      public void fireStateChanged() {
65          // Guaranteed to return a non-null array
66          Object[] listeners = listenerList.getListenerList();
67          // Process the listeners last to first, notifying
68          // those that are interested in this event
69          for (int i = listeners.length-2; i>=0; i-=2) {
70              if (listeners[i]==ChangeListener.class) {
71                  // Lazily create the event:
72                  if (changeEvent == null)
73                      changeEvent = new ChangeEvent(eventSource);
74                  ((ChangeListener)listeners[i+1]).stateChanged(changeEvent);
75              }          
76          }
77      }   
78  
79  }