Is this your first time here? SwingWiki is a Java Swing Developer community site with an big archive of Swing-related usenet groups and mailing lists, but also tips, tricks and articles and book reviews written by your colleagues from around the world. If you came here through a search engine and did not find what you were looking for, make sure to check the wiki table of contents.

Use SwingUtilities for visual modifications

In multi-threaded Swing applications, always use the ''SwingUtilities'' class to perform visual updates (except when working directly in event handlers).

Remember three static methods of that class - invokeLater(Runnable), invokeAndWait(Runnable) and isEventDispatchThread(). First executes the run() method of the parameter asynchronously with the Event Dispatch Thread, the other executes it synchronously, and the third checks if the current Thread is the Event Dispatch Thread.

The first method waits for all pending events to be processed and then processes the visual update, but does not block. The second blocks until all pending events are processed, and the run() method of the parameter returns. Method invokeAndWait() should never be called from the event dispatch thread - it will throw an Exception in that case. If you are unsure about the current thread, use isEventDispatchThread() to check.

If you have a method that must be called on the Swing EventDispatchThread then you can use the following code template (note all the arguments must be declared as final).

    public void someMethod(final String msg) {
        if (!SwingUtilities.isEventDispatchThread()) {
            SwingUtilities.invokeLater( new Runnable() {
                public void run() {
        //  actual code for this someMethod goes here
        // will always be run on the swing EventDispatchThread

See also Swing Threading.


Comments? Corrections? Contact us or Login to edit pages directly (registration is free and takes less than displaying a JLabel)
  best/use_swingutilities.txt · Last modified: 2006/01/14 02:50 by (drmpf)
Recent changes | RSS changes | Table of contents | News Archive | Terms And Conditions | Register | The Quest For Software++| Ruby Resources

Sedo - Buy and Sell Domain Names and Websites project info: Statistics for project etracker� web controlling instead of log file analysis