Java Reference
In-Depth Information
16.16
Why does the ActionListener interface have no listener interface adapter?
Check
16.17
What is the advantage of using a listener interface adapter rather than a listener
interface?
Point
16.10 Key Events
A key event is fired whenever a key is pressed, released, or typed on a component.
Key
Point
Key events enable the use of the keys to control and perform actions or get input from the key-
board. The KeyEvent object describes the nature of the event (namely, that a key has been
pressed, released, or typed) and the value of the key, as shown in Figure 16.15. Java provides
the KeyListener interface to handle key events, as shown in Figure 16.16.
java.awt.event.InputEvent
java.awt.event.KeyEvent
+getKeyChar(): char
Returns the character associated with the key in this event.
+getKeyCode(): int
Returns the integer key code associated with the key in this event.
F IGURE 16.15
The KeyEvent class encapsulates information about key events.
«interface»
java.awt.event.KeyListener
+ keyPressed(e: KeyEvent): void
Invoked after a key is pressed on the source component.
+ keyReleased(e: KeyEvent): void
Invoked after a key is released on the source component.
Invoked after a key is pressed and then released on the source component.
+ keyTyped(e: KeyEvent): void
F IGURE 16.16
The KeyListener interface handles key pressed, released, and typed events.
The keyPressed handler is invoked when a key is pressed, the keyReleased handler is
invoked when a key is released, and the keyTyped handler is invoked when a Unicode char-
acter is entered. If a key does not have a Unicode (e.g., function keys, modifier keys, action
keys, and control keys), the keyTyped handler will not be invoked.
Every key event has an associated key character or key code that is returned by the
getKeyChar() or getKeyCode() method in KeyEvent . The key codes are constants
defined in the KeyEvent class. Table 16.3 lists some constants. See the Java API for a
complete list of the constants. For a key of the Unicode character, the key code is the same
as the Unicode value. For the key-pressed and key-released events, getKeyCode() returns
the value as defined in the table. For the key-typed event, getKeyCode() returns
VK_UNDEFINED ( 0 ), and getKeyChar() returns the character entered.
The program in Listing 16.9 displays a user-input character. The user can move the
character up, down, left, and right, using the arrow keys VK_UP , VK_DOWN , VK_LEFT , and
VK_RIGHT . Figure 16.17 contains a sample run of the program.
 
 
 
Search WWH ::




Custom Search