KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > snow > utils > gui > SwingSafeRunnable


1 package snow.utils.gui;
2
3 import javax.swing.SwingUtilities JavaDoc;
4
5
6 /** a runnable wrapper class which guaranties that
7  * the runnable given runs in the dispatch thread.
8  *
9  * BE CAREFUL, the word "Safe" is excessive. It just assure
10  * that you don't become exceptions if you try to naively
11  * perform a SwingUtilities.invokeAndWait from the event dispatch thread.
12  *
13  * It's always better if you exactely know in which thread
14  * you're running.
15  */

16 public class SwingSafeRunnable implements Runnable JavaDoc {
17
18     Runnable JavaDoc 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 JavaDoc theRunnable, boolean doWait) {
25         runnable = theRunnable;
26         wait = doWait;
27     }
28
29     public void run()
30     {
31       try
32       {
33         if(SwingUtilities.isEventDispatchThread()) {
34             runnable.run();
35         }
36         else
37         {
38             if(wait)
39             {
40                 try {
41                     SwingUtilities.invokeAndWait(runnable);
42                 }
43                 catch (InterruptedException JavaDoc iE)
44                 {
45                   iE.printStackTrace();
46                 }
47                 catch (java.lang.reflect.InvocationTargetException JavaDoc iTE)
48                 {
49                   iTE.printStackTrace();
50                 }
51             }
52             else
53                 SwingUtilities.invokeLater(runnable);
54         }
55       }
56       catch(Exception JavaDoc e)
57       {
58          // ### test
59
e.printStackTrace();
60          throw new RuntimeException JavaDoc(e.getMessage());
61       }
62     }
63
64
65 }
66
Popular Tags