Multithreading in Swing

Multithreading programs need to be careful about updating Swing components. The issue arises because Swing has its own event-dispatching thread. If your application is changing components in a different thread, bad things might happen: misshapen components or race conditions.

The fundamental rule is simple: if you need to update a Swing component from your own thread, do it using invokeAndWait( ) or invokeLater( ). These are static methods in the javax.swing.SwingUtilities class.

public static void invokeLater (Runnable doRun )

Use this method to ask Swing to execute the run( ) method of the specified Runnable.

public static void invokeAndWait (Runnable doRun )throws InterruptedException,InvocationTargetException

This method is just like invokeLater( ), except that it waits until the run( ) method has completed before returning.

A simple example is a download progress indicator. If your application downloads a lot of data from the network, it should show a progress meter that indicates how much data has been downloaded and how much remains. You shouldn’t update this meter directly from the download thread; instead, you should package updates in a Runnable and use invokeLater( ) or invokeAndWait( ).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset