01: package snow.utils.gui;
02:
03: import javax.swing.SwingUtilities;
04:
05: /** a runnable wrapper class which guaranties that
06: * the runnable given runs in the dispatch thread.
07: *
08: * BE CAREFUL, the word "Safe" is excessive. It just assure
09: * that you don't become exceptions if you try to naively
10: * perform a SwingUtilities.invokeAndWait from the event dispatch thread.
11: *
12: * It's always better if you exactely know in which thread you're running.
13: * you can avoid creating runnable and call directly the code, if you know being in the EDT.
14: * use this only for strenghtening code that can be called in all contexts.
15: */
16: public class SwingSafeRunnable implements Runnable {
17:
18: Runnable runnable;
19: boolean wait;
20:
21: /** @param theRunnable is the runnable to execute
22: * @param doWait true if we must
23: */
24: public SwingSafeRunnable(Runnable theRunnable, boolean doWait) {
25: runnable = theRunnable;
26: wait = doWait;
27: }
28:
29: public static void invokeLater(Runnable r) {
30: new SwingSafeRunnable(r, false).run();
31: }
32:
33: public static void invokeAndWait(Runnable r) {
34: new SwingSafeRunnable(r, true).run();
35: }
36:
37: public void run() {
38: try {
39: if (SwingUtilities.isEventDispatchThread()) {
40: runnable.run();
41: } else {
42: if (wait) {
43: try {
44: SwingUtilities.invokeAndWait(runnable);
45: } catch (InterruptedException iE) {
46: iE.printStackTrace();
47: throw new RuntimeException("interrupted", iE); // important !
48: } catch (java.lang.reflect.InvocationTargetException iTE) {
49: iTE.printStackTrace();
50: }
51: } else
52: SwingUtilities.invokeLater(runnable);
53: }
54: } catch (Exception e) {
55: // ### test
56: e.printStackTrace();
57: throw new RuntimeException(e.getMessage());
58: }
59: }
60:
61: }
|