Java Reference
In-Depth Information
SR 8.31 Which mouse events are responded to in the Dots program? Which are
responded to in the RubberLines program?
SR 8.32 Suppose you are creating a GUI to support a program that plays
Tic-Tac-Toe against the user. Describe how your program might
respond to various mouse events.
8.9 Key Events
A key event is generated when a keyboard key is pressed.
Key events allow a program to respond immediately to the
user while he or she is typing or pressing other keyboard keys
such as the arrow keys. If key events are being processed, the
program can respond as soon as the key is pressed; there is
no need to wait for the Enter key to be pressed or for some
other component (like a button) to be activated.
The Direction program shown in Listing 8.21 responds to key events. An
image of an arrow is displayed, and the image moves across the screen as the
arrow keys are pressed. Actually, four different images are used, one each for the
arrow pointing in each of the primary directions (up, down, right, and left).
The DirectionPanel class, shown in Listing 8.22, represents the panel on
which the arrow image is displayed. The constructor loads the four arrow images,
one of which is always considered to be the current image (the one displayed).
The current image is set based on the arrow key that was most recently pressed.
For example, if the up arrow is pressed, the image with the arrow pointing up is
displayed. If an arrow key is continually pressed, the appropriate image “moves”
in the appropriate direction.
The arrow images are managed as ImageIcon objects. In this example, the
image is drawn using the paintIcon method each time the panel is repainted.
The paintIcon method takes four parameters: a component to serve as an
KEY CONCEPT
Key events allow a program to
respond immediately to the user
pressing keyboard keys.
image
observer , the graphics context on which the image will be drawn, and the ( x , y )
coordinates where the image is drawn. An image observer is a component that
serves to manage image loading; in this case we use the panel as the image observer.
The private inner class called DirectionListener is set up to respond to key
events. It implements the KeyListener interface, which defines three methods that
we can use to respond to keyboard activity. Figure 8.8 lists these methods.
Specifically, the Direction program responds to key pressed events. Because
the listener class must implement all methods defined in the interface, we provide
empty methods for the other events.
 
Search WWH ::




Custom Search