Java tutorial
//package com.java2s; import java.lang.reflect.InvocationTargetException; import javax.swing.SwingUtilities; public class Main { /** * Execute the given runnable code dedicated to Swing using the Event Dispatcher Thread (EDT) * And waits for completion * @param runnable runnable code dedicated to Swing * @throws IllegalStateException if any exception occurs while the given runnable code executes using EDT */ public static void invokeAndWaitEDT(final Runnable runnable) throws IllegalStateException { if (isEDT()) { // current Thread is EDT, simply execute runnable: runnable.run(); } else { // If the current thread is interrupted, then use invoke later EDT (i.e. do not wait): if (Thread.currentThread().isInterrupted()) { invokeLaterEDT(runnable); } else { try { // Using invokeAndWait to be in sync with the calling thread: SwingUtilities.invokeAndWait(runnable); } catch (InterruptedException ie) { // propagate the exception because it should never happen: throw new IllegalStateException( "SwingUtils.invokeAndWaitEDT : interrupted while running " + runnable, ie); } catch (InvocationTargetException ite) { // propagate the internal exception : throw new IllegalStateException( "SwingUtils.invokeAndWaitEDT : an exception occured while running " + runnable, ite.getCause()); } } } } /** * Returns true if the current thread is the Event Dispatcher Thread (EDT) * * @return true if the current thread is the Event Dispatcher Thread (EDT) */ public static boolean isEDT() { return SwingUtilities.isEventDispatchThread(); } /** * Execute LATER the given runnable code dedicated to Swing using the Event Dispatcher Thread (EDT) * @param runnable runnable code dedicated to Swing */ public static void invokeLaterEDT(final Runnable runnable) { // current Thread is NOT EDT, simply invoke later runnable using EDT: SwingUtilities.invokeLater(runnable); } }