Java Reference
In-Depth Information
TABLE 12-14
Events Generated by the Keyboard and Mouse
Event Generated
Listener Interface
Listener Method
key
KeyEvent
KeyListener
keyPressed
key
KeyEvent
KeyListener
keyReleased
key
KeyEvent
KeyListener
keyTyped
mouse
MouseEvent
MouseListener
mouseClicked
mouse
MouseEvent
MouseListener
mouseEntered
mouse
MouseEvent
MouseListener
mouseExited
mouse
MouseEvent
MouseListener
mousePressed
mouse
MouseEvent
MouseListener
mouseReleased
mouse
MouseEvent
MouseMotionListener
mouseDragged
mouse
MouseEvent
MouseMotionListener
mouseMoved
Key Events
This section describes how to handle key events. As shown in Table 12-14, there are
three types of key events. The
interface
KeyListener
contains the methods—
keyPressed
,
keyReleased
, and
keyTyped
—that correspond to these events. These
methods specify the action that needs to be taken when a key event occurs. When you
press a meta key (such as Control, Shift, or Alt), the method
keyPressed
is executed;
when you type a regular alphanumeric key, the method
keyTyped
is executed.
When you release any key, the method
keyReleased
is executed. The program in
Example 12-8 shows how to handle key events.
EXAMPLE 12-8
This program displays the character that corresponds to the key typed by the user. For
example, if the user presses the key
A
, the program displays
A
. We use a
JTextField
object to display the character.
When you type an alphanumeric key, a key event is generated. The key event is handled
by the method
keyTyped
. The necessary code to display the key is placed in the body of
the method
keyTyped
. Before displaying the key typed by the user, the previous
character is removed from the
JTextField
object. In other words, the program displays
only one character at a time, corresponding to the key typed. In this program, the font of
the character is set to
Courier
and the color of the character is randomly selected.
Because the interface
keyListener
contains three methods and we want to implement
only one of these methods, we use the anonymous class mechanism to register a listener
Search WWH ::
Custom Search