Advertisement
tpeierls

SwingScope

Jun 27th, 2011
566
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.73 KB | None | 0 0
  1. /*
  2.  * This source code is released into the public domain by its author, Tim Peierls.
  3.  */
  4. package com.example;
  5.  
  6. import com.google.inject.Key;
  7. import com.google.inject.Provider;
  8. import com.google.inject.Scope;
  9.  
  10. import java.lang.reflect.InvocationTargetException;
  11. import java.util.concurrent.atomic.AtomicReference;
  12.  
  13. import javax.swing.SwingUtilities;
  14.  
  15. /**
  16.  * Scope that arranges to perform its provision in the EDT.
  17.  */
  18. public class SwingScope implements Scope {
  19.     public <T> Provider<T> scope(Key<T> key, final Provider<T> unscoped) {
  20.         return new Provider<T>() {
  21.             public T get() {
  22.                 if (SwingUtilities.isEventDispatchThread()) {
  23.                     return unscoped.get();
  24.                 }
  25.                 final AtomicReference<T> result = new AtomicReference<T>();
  26.                 try {
  27.                     SwingUtilities.invokeAndWait(new Runnable() {
  28.                         public void run() {
  29.                             result.set(unscoped.get());
  30.                         }
  31.                     });
  32.                 } catch (InterruptedException ex) {
  33.                     Thread.currentThread().interrupt();
  34.                 } catch (InvocationTargetException ex) {
  35.                     Throwable t = ex.getTargetException();
  36.                     if (t instanceof RuntimeException) {
  37.                         throw (RuntimeException) t;
  38.                     } else if (t instanceof Error) {
  39.                         throw (Error) t;
  40.                     } else {
  41.                         throw new RuntimeException(t);
  42.                     }
  43.                 }
  44.                 return result.get();
  45.             }
  46.         };
  47.     }
  48.  
  49.     public String toString() {
  50.         return "SwingScope";
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement