1 /*
2 * Copyright 2006-2016 The JGUIraffe Team.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License")
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package net.sf.jguiraffe.gui.platform.swing.builder.utils;
17
18 import java.awt.EventQueue;
19 import java.lang.reflect.InvocationTargetException;
20
21 import net.sf.jguiraffe.gui.builder.utils.GUIRuntimeException;
22 import net.sf.jguiraffe.gui.builder.utils.GUISynchronizer;
23
24 /**
25 * <p>
26 * The Swing specific implementation of the <code>GUISynchronizer</code>
27 * interface.
28 * </p>
29 * <p>
30 * This implementation makes uses of <code>java.awt.EventQueue</code> to
31 * properly deal with the event dispatch thread.
32 * </p>
33 *
34 * @author Oliver Heger
35 * @version $Id: SwingGUISynchronizer.java 205 2012-01-29 18:29:57Z oheger $
36 */
37 public class SwingGUISynchronizer implements GUISynchronizer
38 {
39 /**
40 * Invokes the given runnable asynchronously on the event dispatch thread.
41 * This is done using the <code>java.awt.EventQueue</code> class.
42 *
43 * @param runnable the runnable to be executed
44 */
45 public void asyncInvoke(Runnable runnable)
46 {
47 EventQueue.invokeLater(runnable);
48 }
49
50 /**
51 * Invokes the given runnable synchronously on the event dispatch thread.
52 * This is done using the <code>java.awt.EventQueue</code> class. It will
53 * cause no harm if this method is invoked from the event dispatch thread;
54 * then the runnable will be directly called.
55 *
56 * @param runnable the runnable to be executed
57 */
58 public void syncInvoke(Runnable runnable)
59 {
60 if (isEventDispatchThread())
61 {
62 runnable.run();
63 }
64 else
65 {
66 try
67 {
68 EventQueue.invokeAndWait(runnable);
69 }
70 catch (InterruptedException iex)
71 {
72 throw new GUIRuntimeException("Thread was interrupted!", iex);
73 }
74 catch (InvocationTargetException itex)
75 {
76 throw new GUIRuntimeException("Runnable threw exception", itex);
77 }
78 }
79 }
80
81 /**
82 * Tests if the current thread is the event dispatch thread.
83 *
84 * @return a flag if this method is called on the event dispatch thread
85 */
86 public boolean isEventDispatchThread()
87 {
88 return EventQueue.isDispatchThread();
89 }
90 }