01: /*
02: * @(#)Worker.java 2.1 2005-10-16
03: *
04: * Copyright (c) 1998-2005 Werner Randelshofer
05: * Staldenmattweg 2, Immensee, CH-6405, Switzerland.
06: * All rights reserved.
07: *
08: * This software is the confidential and proprietary information of
09: * Werner Randelshofer. ("Confidential Information"). You shall not
10: * disclose such Confidential Information and shall use it only in
11: * accordance with the terms of the license agreement you entered into
12: * with Werner Randelshofer.
13: */
14: //package ch.randelshofer.util;
15: package contrib.ch.randelshofer.quaqua.util;
16:
17: import java.awt.ActiveEvent;
18: import javax.swing.SwingUtilities;
19:
20: /**
21: * This is an abstract class that you subclass to
22: * perform GUI-related work in a dedicated event dispatcher.
23: * <p>
24: * This class is similar to SwingWorker but less complex.
25: * Like a SwingWorker it can run using an an internal
26: * worker thread but it can also be like a Runnable object.
27: *
28: * @author Werner Randelshofer
29: * @version 2.1 2005-10-16 Method start() added.
30: * <br>2.0 2005-09-27 Revised.
31: * <br>1.1.1 2001-08-24 Call finished() within finally block.
32: * <br>1.1 2001-08-24 Reworked for JDK 1.3.
33: * <br>1.0 1998-10-07 Created.
34: */
35: public abstract class Worker implements Runnable {
36: private Object value; // see getValue(), setValue()
37:
38: /**
39: * Calls #construct on the current thread and invokes
40: * #finished on the AWT event dispatcher thread.
41: */
42: public final void run() {
43: final Runnable doFinished = new Runnable() {
44: public void run() {
45: finished(getValue());
46: }
47: };
48: try {
49: setValue(construct());
50: } catch (Throwable e) {
51: e.printStackTrace();
52: } finally {
53: SwingUtilities.invokeLater(doFinished);
54: }
55: }
56:
57: /**
58: * Compute the value to be returned by the <code>get</code> method.
59: */
60: public abstract Object construct();
61:
62: /**
63: * Called on the event dispatching thread (not on the worker thread)
64: * after the <code>construct</code> method has returned.
65: *
66: * @param value The return value of the construct method.
67: */
68: public abstract void finished(Object value);
69:
70: /**
71: * Get the value produced by the worker thread, or null if it
72: * hasn't been constructed yet.
73: */
74: protected synchronized Object getValue() {
75: return value;
76: }
77:
78: /**
79: * Set the value produced by worker thread
80: */
81: private synchronized void setValue(Object x) {
82: value = x;
83: }
84:
85: /**
86: * Starts the Worker on an internal worker thread.
87: */
88: public void start() {
89: new Thread(this).start();
90: }
91: }
|