View Javadoc

1   /*
2    * @(#)$Id: Mapping.java 689 2009-07-22 00:10:27Z bsigner $
3    *
4    * Author       :   Ueli Kurmann, igesture@uelikurmann.ch
5    *
6    * Purpose      :   EDT Proxy. Executes all methods in the EDT.
7    *
8    * -----------------------------------------------------------------------
9    *
10   * Revision Information:
11   *
12   * Date             Who         Reason
13   *
14   * Aug 14, 2008     ukurmann    Initial Release
15   *
16   * -----------------------------------------------------------------------
17   *
18   * Copyright 1999-2009 ETH Zurich. All Rights Reserved.
19   *
20   * This software is the proprietary information of ETH Zurich.
21   * Use is subject to license terms.
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  }