Java Reference
In-Depth Information
LISTING 8.22
continued
//--------------------------------------------------------------
// Provide empty definitions for unused event methods.
//--------------------------------------------------------------
public void
keyTyped (KeyEvent event) {}
public void
keyReleased (KeyEvent event) {}
}
}
The
KeyEvent
object passed to the
keyPressed
method of the listener can be
used to determine which key was pressed. In the example, we call the
getKeyCode
method of the event object to get a numeric code that represents the key that was
pressed. We use a
switch
statement to determine which key was pressed and to
respond accordingly. The
KeyEvent
class contains constants that correspond to
the numeric code that is returned from the
getKeyCode
method. If any key other
than an arrow key is pressed, it is ignored.
void
keyPressed (KeyEvent event)
Called when a key is pressed.
void
keyReleased (KeyEvent event)
Called when a key is released.
void
keyTyped (KeyEvent event)
Called when a pressed key or key combination produces
a key character.
FIGURE 8.8
The methods of the
KeyListener
interface
Search WWH ::
Custom Search