01: package abbot.util;
02:
03: import java.awt.*;
04: import java.awt.event.*;
05: import java.lang.ref.*;
06:
07: /** Provides add-and-forget listening to the AWT event queue.
08: * Provides an AWTEventListener which will automatically disconnect the
09: * target listener when the target gets garbage-collected. Once the target
10: * is GC'd, this listener will remove itself from the AWT event listener list.
11: */
12: public class WeakAWTEventListener implements AWTEventListener {
13:
14: private WeakReference listener;
15:
16: public WeakAWTEventListener(AWTEventListener l, long mask) {
17: listener = new WeakReference(l);
18: Toolkit.getDefaultToolkit().addAWTEventListener(this , mask);
19: }
20:
21: public void dispose() {
22: Toolkit.getDefaultToolkit().removeAWTEventListener(this );
23: }
24:
25: public void eventDispatched(AWTEvent e) {
26: AWTEventListener l = (AWTEventListener) listener.get();
27: if (l != null) {
28: l.eventDispatched(e);
29: } else {
30: dispose();
31: }
32: }
33: }
|