01: package org.gui4j.event;
02:
03: import java.util.ArrayList;
04: import java.util.List;
05:
06: /**
07: * An event is fired only if the <code>fireEvent</code> method is called
08: */
09: public class SimpleEvent implements Gui4jEvent {
10: private final List listeners;
11: private boolean enabled = true;
12:
13: public SimpleEvent() {
14: listeners = new ArrayList();
15: }
16:
17: public synchronized void addEventListener(
18: Gui4jEventListener listener) {
19: listeners.add(listener);
20: }
21:
22: public synchronized void removeEventListener(
23: Gui4jEventListener listener) {
24: listeners.remove(listener);
25: }
26:
27: public final void fireEvent() {
28: if (enabled) {
29: // We take a snapshot of the listeners in a synchronized
30: // block but notify the listeners outside of it.
31: // Otherwise we have a Concurrent Modification problem if
32: // the notification code tries to add or remove a listener.
33: Object[] listenersSnapshot;
34: synchronized (this ) {
35: listenersSnapshot = listeners.toArray();
36: }
37: for (int i = listenersSnapshot.length - 1; i >= 0; i--) {
38: ((Gui4jEventListener) listenersSnapshot[i])
39: .eventOccured();
40: }
41: }
42: }
43:
44: /**
45: * Returns the enabled.
46: * @return boolean
47: */
48: public boolean isEnabled() {
49: return enabled;
50: }
51:
52: /**
53: * Sets the enabled.
54: * @param enabled The enabled to set
55: */
56: public void setEnabled(boolean enabled) {
57: this.enabled = enabled;
58: }
59:
60: }
|