01: /*
02: * Sun Public License Notice
03: *
04: * The contents of this file are subject to the Sun Public License
05: * Version 1.0 (the "License"). You may not use this file except in
06: * compliance with the License. A copy of the License is available at
07: * http://www.sun.com/
08: *
09: * The Original Code is NetBeans. The Initial Developer of the Original
10: * Code is Sun Microsystems, Inc. Portions Copyright 1997-2000 Sun
11: * Microsystems, Inc. All Rights Reserved.
12: */
13:
14: package org.netbeans.editor;
15:
16: import java.awt.event.ActionEvent;
17: import java.awt.event.ActionListener;
18: import java.lang.ref.WeakReference;
19:
20: import javax.swing.Timer;
21:
22: /**
23: * Action listener that has a weak reference to the source action listener so it
24: * doesn't prevent it to be garbage collected. The calls to the
25: * <code>actionPerformed</code> are automatically propagated to the source
26: * action listener.
27: *
28: * @author Miloslav Metelka
29: * @version 1.00
30: */
31:
32: public class WeakTimerListener implements ActionListener {
33:
34: private WeakReference ref;
35:
36: private boolean stopTimer;
37:
38: /**
39: * Construct new listener with automatic timer stopping.
40: */
41: public WeakTimerListener(ActionListener source) {
42: this (source, true);
43: }
44:
45: /**
46: * Construct new listener.
47: *
48: * @param source
49: * source action listener to which this listener delegates.
50: * @param stopTimer
51: * whether the timer should be stopped automatically when the
52: * timer fires and the source listener was garbage collected.
53: */
54: public WeakTimerListener(ActionListener source, boolean stopTimer) {
55: this .ref = new WeakReference(source);
56: this .stopTimer = stopTimer;
57: }
58:
59: public void actionPerformed(ActionEvent evt) {
60: ActionListener src = (ActionListener) ref.get();
61: if (src != null) {
62: src.actionPerformed(evt);
63:
64: } else { // source listener was garbage collected
65: if (evt.getSource() instanceof Timer) {
66: Timer timer = (Timer) evt.getSource();
67: timer.removeActionListener(this);
68:
69: if (stopTimer) {
70: timer.stop();
71: }
72: }
73: }
74: }
75:
76: }
|