1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 package org.ximtec.igesture.tool.core;
26
27 import java.lang.reflect.InvocationHandler;
28 import java.lang.reflect.Method;
29 import java.lang.reflect.Proxy;
30 import java.util.logging.Level;
31 import java.util.logging.Logger;
32
33 import javax.swing.SwingUtilities;
34
35 public class EdtProxy implements InvocationHandler {
36
37 private static final Logger LOGGER = Logger.getLogger(EdtProxy.class.getName());
38
39 private Object view;
40
41 private EdtProxy(Object view) {
42 this.view = view;
43 }
44
45 @Override
46 public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
47
48 final Object[] results = new Object[1];
49
50 if (SwingUtilities.isEventDispatchThread()) {
51 try {
52 results[0] = method.invoke(view, args);
53 } catch (Exception e) {
54 LOGGER.log(Level.SEVERE, "Invocation Error. Already in EDT.", e);
55 }
56 } else {
57 SwingUtilities.invokeAndWait(new Runnable() {
58
59 @Override
60 public void run() {
61 try {
62 results[0] = method.invoke(view, args);
63 } catch (Exception e) {
64 LOGGER.log(Level.SEVERE, "Invocation Error.", e);
65 }
66
67 }
68 });
69 }
70
71 return results[0];
72 }
73
74 public static <T> T newInstance(T view, Class<T> type) {
75
76 return type.cast(Proxy.newProxyInstance(view.getClass().getClassLoader(), view.getClass().getInterfaces(),
77 new EdtProxy(view)));
78 }
79
80 }