To avoid problems (including the potential for deadlock), all Swing GUI components must
be created and updated from the event dispatching thread, not the main thread of the
application. However, main( ) is executed on the main thread. Thus, main( ) cannot directly
instantiate a SwingDemo object. Instead, it must create a Runnable object that executes on
the event dispatching thread and have this object create the GUI.
To enable the GUI code to be created on the event dispatching thread, you must use one of
two methods that are defined by the SwingUtilities class. These methods are invokeLater( )
and invokeAndWait( ). They are shown here:
static void invokeLater(Runnable obj)
static void invokeAndWait(Runnable obj)
throws InterruptedException, InvocationTargetException
Here, obj is a Runnable object that will have its run( ) method called by the event dispatching
thread. The difference between the two methods is that invokeLater( ) returns immediately,
but invokeAndWait( ) waits until obj.run( ) returns. You can use one of these methods to
call a method that constructs the GUI for your Swing application, or whenever you need to
modify the state of the GUI from code not executed by the event dispatching thread. You
will normally want to use invokeLater( ), as the preceding program does. However, when
constructing the initial GUI for an applet, you will need to use invokeAndWait( ).
The preceding example showed the basic form of a Swing program, but it left out one
important part: event handling. Because JLabel does not take input from the user, it does
not generate events, so no event handling was needed. However, the other Swing components
do respond to user input and the events generated by those interactions need to be handled.
Events can also be generated in ways not directly related to user input. For example, an
event is generated when a timer goes off. Whatever the case, event handling is a large part
of any Swing-based application.
The event handling mechanism used by Swing is the same as that used by the AWT.
This approach is called the delegation event model, and it is described in Chapter 22. In many
cases, Swing uses the same events as does the AWT, and these events are packaged in
java.awt.event. Events specific to Swing are stored in javax.swing.event.
Although events are handled in Swing in the same way as they are with the AWT, it is
still useful to work through a simple example. The following program handles the event
generated by a Swing push button. Sample output is shown in Figure 29-2.
Output from the EventDemo program
Search WWH :