Java Reference
In-Depth Information
public void keyPressed (int keyCode) {
if (getGameAction (keyCode) == FIRE)
javagochi.transform (10);
}
Now you can save the Javagochi from starvation using the FIRE game key.
Canvas and Text Input
As mentioned in the introduction to interaction, it is not possible to receive composed key events using
the low-level API. But what can you do if you need this kind of input, such as for a text input trainer?
Let's just assume simple feeding is not enough for your Javagochi . Depending on its current state, it
needs special vitamins, denoted by letters ranging from A to Z. On phones providing keys 0 through 9
only, this is a problem. The only solution is to emulate the key input mechanism in software. On
cellular phones, there are also three to four letters printed on the number keys. In text input mode,
pressing a number makes the first letter appear. If the same number is pressed again in a limited period
of time, the second letter appears instead of the first one. This way you can cycle through all the letters
on a number key. When no key is pressed for about three quarters of a second, or another key is pressed,
the letter currently displayed is confirmed as input key.
For emulation of this mechanism, you define the letters on the keys 2 through 9 in a String array
inside the Face class:
public static final String[] keys = {"abc", "def", "ghi", "jkl",
"mno", "pqrs", "tuv", "wxyz"} ;
You also need a timer to measure the time until confirmation of the current key. The timer is stored in
keyTimer . The variables keyMajor and keyMinor contain the index in the keys array and the
index inside the corresponding string. The variable needed stores the vitamin currently needed by the
Javagochi :
Timer keyTimer;
int keyMajor = -1;
int keyMinor;
char needed = 'a';
What do you do if a numeric key is pressed? If you already have a timer running, you cancel it since a
key was pressed. Then, you subtract the code of the 2 key from the current key code in order to
calculate the index in your key array. If the given event does not represent a numeric key between 2
and 9, you set keyMajor to the special value -1, denoting that no valid character is being entered.
Otherwise, you check whether the key is identical to the last key. If so, keyMinor is incremented in
order to cycle through the letters assigned to a single numeric key. If another key is pressed,
keyMajor is changed accordingly and keyMinor is set back to 0. A new timer is scheduled for half
a second later:
public synchronized void keyPressed (int keyCode) {
if (keyTimer != null) keyTimer.cancel();
int index = keyCode - KEY_NUM2;
if (index < 0 || index > keys.length)
keyMajor = -1;
else {
if (index != keyMajor) {
keyMinor = 0;
keyMajor = index;
Search WWH ::




Custom Search