1 18 package org.apache.batik.util; 19 20 import java.awt.EventQueue ; 21 import java.util.List ; 22 import java.lang.reflect.InvocationTargetException ; 23 24 30 public class EventDispatcher { 31 32 public interface Dispatcher { 33 public void dispatch(Object listener, 34 Object event); 35 } 36 37 38 public static void fireEvent(final Dispatcher dispatcher, 39 final List listeners, 40 final Object evt, 41 final boolean useEventQueue) { 42 if (useEventQueue && !EventQueue.isDispatchThread()) { 43 Runnable r = new Runnable () { 44 public void run() { 45 fireEvent(dispatcher, listeners, evt, useEventQueue); 46 } 47 }; 48 try { 49 EventQueue.invokeAndWait(r); 50 } catch (InvocationTargetException e) { 51 e.printStackTrace(); 52 } catch (InterruptedException e) { 53 } catch (ThreadDeath td) { 56 throw td; 57 } catch (Throwable t) { 58 t.printStackTrace(); 59 } 60 return; 61 } 62 63 Object [] ll = null; 64 Throwable err = null; 65 int retryCount = 10; 66 while (--retryCount != 0) { 67 try { 71 synchronized (listeners) { 72 if (listeners.size() == 0) 73 return; 74 ll = listeners.toArray(); 75 break; 76 } 77 } catch(Throwable t) { 78 err = t; 79 } 80 } 81 if (ll == null) { 82 if (err != null) 83 err.printStackTrace(); 84 return; 85 } 86 dispatchEvent(dispatcher, ll, evt); 87 } 88 89 protected static void dispatchEvent(final Dispatcher dispatcher, 90 final Object [] ll, 91 final Object evt) { 92 ThreadDeath td = null; 93 try { 94 for (int i = 0; i < ll.length; i++) { 95 try { 96 Object l; 97 synchronized (ll) { 98 l = ll[i]; 99 if (l == null) continue; 100 ll[i] = null; 101 } 102 dispatcher.dispatch(l, evt); 103 } catch (ThreadDeath t) { 104 td = t; 106 } catch (Throwable t) { 107 t.printStackTrace(); 108 } 109 } 110 } catch (ThreadDeath t) { 111 td = t; 113 } catch (Throwable t) { 114 if (ll[ll.length-1] != null) 115 dispatchEvent(dispatcher, ll, evt); 116 t.printStackTrace(); 117 } 118 if (td != null) throw td; 119 } 120 } 121 | Popular Tags |