Swing Invocation Helper
Developer's Cave, Island Forge June 18th. 2008, 11:00am
This article presents a simple programming technique for ensuring Java Swing tasks are executed on the proper thread, while avoiding unnecessary delayed invocation.
When programming with Java Swing, all method calls must execute on the event dispatch thread (else chaos ensues). If your application drives Swing components, you must insulate Swing from other threads. The standard approach is to create a
In my Potential RPG Swing GUI code, this utility allows certain methods to accept calls from both Swing and non-Swing sources, handling Swing updates cleanly in either case.
Runnable task, passing it to SwingUtilities.invokeLater(Runnable).
Notice that invokeLater places the task on the tail of the event dispatch queue, to be processed by the event dispatch thread at Swing's earliest convenience. Handing off the task properly insulates Swing from other threads.
However, consider the situation in which the calling thread does happen to be the event dispatch thread. In this case, it is usually preferable to immediately execute the task (else a visible "stutter" can occur in GUI updates).
The following method (placed in a utility class) executes a task in-line if called on the event dispatch thread, or postpones execution if called from another thread:
public static void invoke(final Runnable task) { if (SwingUtilities.isEventDispatchThread()) { task.run(); } else { SwingUtilities.invokeLater(task); } }
Leave a Reply
You must be logged in to post a comment.













