GUI event handling and painting code executes in a single thread called the event dispatcher thread . This ensures that each event handler finishes executing before the next one executes and the painting isn't interrupted by events.
In certain situations, you need to run the code in the event dispatcher thread to avoid possible deadlock. You can use the static methods , invokeLater and invokeAndWait , in the javax.swing.SwingUtilities class to run the code in the event dispatcher thread. You must put this code in the run method of a Runnable object and specify the Runnable object as the argument to invokeLater and invokeAndWait . The invokeLater method returns immediately, without waiting for the event dispatcher thread to execute the code. The invokeAndWait method is just like invokeLater , except that invokeAndWait doesn't return until the event-dispatching thread has executed the specified code.
So far, you have launched your GUI application from the main method by creating a frame and making it visible. This works fine for most applications. In certain situations, however, it could cause problems. To avoid possible thread deadlock, you should launch GUI creation from the event dispatcher thread, as follows :
public static void main(String[] args) { SwingUtilities.invokeLater( new Runnable() { public void run() { // Place the code for creating a frame and setting it properties } }); }
For example, Listing 24.3 gives a simple program that launches the frame from the event dispatcher thread.
1 import javax.swing.*; 2 3 public class EventDispatcherThreadDemo extends JApplet { 4 public EventDispatcherThreadDemo() { 5 add( new JLabel( "Hi, it runs from an event dispatcher thread" )); 6 } 7 8 /** Main method */ 9 public static void main(String[] args) { 10 SwingUtilities.invokeLater( new Runnable() { 11 public void run() { 12 JFrame frame = new JFrame( "EventDispatcherThreadDemo" ); 13 frame.add( new EventDispatcherThreadDemo()); 14 frame.setLocationRelativeTo( null ); // Center the frame 15 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 16 frame.setSize( 200 , 200 ); 17 frame.setVisible( true ); 18 } 19 }); 20 } 21 } |