1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.gui.util;
|
---|
3 |
|
---|
4 | import javax.swing.event.ChangeEvent;
|
---|
5 | import javax.swing.event.ChangeListener;
|
---|
6 | import javax.swing.event.EventListenerList;
|
---|
7 |
|
---|
8 | /**
|
---|
9 | * Replacement to {@code java.util.Observable} class, deprecated with Java 9.
|
---|
10 | * @since 10210
|
---|
11 | */
|
---|
12 | public class ChangeNotifier {
|
---|
13 |
|
---|
14 | /** Stores the listeners on this model. */
|
---|
15 | private final EventListenerList listenerList = new EventListenerList();
|
---|
16 |
|
---|
17 | /**
|
---|
18 | * Only one {@code ChangeEvent} is needed per button model
|
---|
19 | * instance since the event's only state is the source property.
|
---|
20 | * The source of events generated is always "this".
|
---|
21 | */
|
---|
22 | private ChangeEvent changeEvent;
|
---|
23 |
|
---|
24 | /**
|
---|
25 | * Adds a {@code ChangeListener}.
|
---|
26 | * @param l the listener to add
|
---|
27 | */
|
---|
28 | public final void addChangeListener(ChangeListener l) {
|
---|
29 | listenerList.add(ChangeListener.class, l);
|
---|
30 | }
|
---|
31 |
|
---|
32 | /**
|
---|
33 | * Removes a {@code ChangeListener}.
|
---|
34 | * @param l the listener to add
|
---|
35 | */
|
---|
36 | public final void removeChangeListener(ChangeListener l) {
|
---|
37 | listenerList.remove(ChangeListener.class, l);
|
---|
38 | }
|
---|
39 |
|
---|
40 | /**
|
---|
41 | * Notifies all listeners that have registered interest for notification on this event type.
|
---|
42 | * The event instance is created lazily.
|
---|
43 | */
|
---|
44 | protected final void fireStateChanged() {
|
---|
45 | // Guaranteed to return a non-null array
|
---|
46 | Object[] listeners = listenerList.getListenerList();
|
---|
47 | // Process the listeners last to first, notifying those that are interested in this event
|
---|
48 | for (int i = listeners.length-2; i >= 0; i -= 2) {
|
---|
49 | if (listeners[i] == ChangeListener.class) {
|
---|
50 | // Lazily create the event:
|
---|
51 | if (changeEvent == null)
|
---|
52 | changeEvent = new ChangeEvent(this);
|
---|
53 | ((ChangeListener) listeners[i+1]).stateChanged(changeEvent);
|
---|
54 | }
|
---|
55 | }
|
---|
56 | }
|
---|
57 | }
|
---|