7.2 Processing on the Event-Dispatching Thread
As we mentioned, all the event callbacks
of your program occur on the
event-dispatching thread. This is good news since it means that most
of the code that needs to access Swing components is automatically
called on the event-dispatching thread.
In our sample typing program, we access Swing components from these
methods:
CharacterDisplayCanvas() CharacterDisplayCanvas.preferredSize() CharacterDisplayCanvas.newCharacter() CharacterDisplayCanvas.paintComponent() SwingTypeTester.initComponents() The actionPerformed() methods of the
SwingTypeTester button objects The keyPressed() method of the
SwingTypeTester canvas ScoreLabel.setScore() AnimatedCharacterDisplayCanvas() AnimatedCharacterDisplayCanvas.newCharacter() AnimatedCharacterDisplayCanvas.paintComponent()
To write a threadsafe Swing program, we must make sure that the
methods listed above are accessed only from within the
event-dispatching thread. Note that this list includes the
constructor for the AnimatedCharacterDisplayCanvas
class; remember that the constructor calls the constructor of its
superclass.
The Swing classes have already made sure that all callbacks occur on
the event-dispatching thread. The preferredSize(), paintComponent(),
keyPressed(), and actionPerformed() methods are all callbacks, so we don't
need to worry about those. The initComponents()
method is called from the main thread of the program, which is not
the event-dispatching thread. The constructor for the display
canvases is called from the same thread. However, the
initComponents() method and its constructors
create the Swing objects; they have not yet been displayed. That
falls into the first exception case that we listed earlier. The
newCharacter() method calls only the
repaint() method, so that falls into the second
exception we listed above. Finally, the setScore() method accesses Swing components only within the
invokeLater() method, so that falls into our
third category. All access to Swing classes within our application is
handled correctly.
The first two exceptions in our list are self-explanatory. In the
next section, we explain the last two exceptions in our list.
|