Java Reference
In-Depth Information
Polling for Keystrokes
Polling for keystrokes is easy: simply use the
getKeyStates
method. This method returns
a bitmask of the pressed key values shown defined in the
GameCanvas
class in Table 8-1;
you can simply use
&
to mask off the flag for the key whose state you seek. Not all of
these keys are available on all devices; for example, many phones don't include hard-
ware to generate the
GAME_A
-
GAME_D
events.
Table 8-1.
Keys Available via getKeyStates
Value
Typical Action
KEY_NUM0
-
KEY_NUM9
Numeric keypad keys 0-9
KEY_POUND
# key
KEY_STAR
* key
LEFT
Left directional key
RIGHT
Right directional key
UP
Up directional key
DOWN
Down directional key
FIRE
OK or center directional key
GAME_A
,
GAME_B
,
GAME_C
,
GAME_D
Custom game keys
■
Caution
As I point out in Chapter 5, not all devices provide all key codes, and some devices map
multiple key codes to the same key. When writing your application, be sure to abstract the key code from
the behavior it embodies using a lookup table or
switch-case
statement so you can accommodate this.
Of course, if you're polling for key state, you don't want to receive key events as
well, so you should pass
true
to your
GameCanvas
'
super
invocation to indicate that
event handling should be disabled. For example, in my game, I might write something
like what's shown in Listing 8-1.