Java Reference
In-Depth Information
KEY_NUM9 , KEY_POUND , and KEY_STAR . Applications should not rely on the presence of any
additional key codes. In particular, upper- and lowercase or characters generated by pressing a key
multiple times are not supported by low-level key events. A "name" assigned to the key can be queried
using the getKeyName() method.
Some keys may have an additional meaning in games. For this purpose, MIDP provides the constants
UP , DOWN , LEFT , RIGHT , FIRE , GAME_A , GAME_B , GAME_C , and GAME_D . The "game" meaning
of a keypress can be determined by calling the getGameAction() method. The mapping from key
codes to game actions is device dependent, so different keys may map to the same game action on
different devices. For example, some devices may have separate cursor keys; others may map the
number pad to four-way movement. Also, several keys may be mapped to the same game code. The
game code can be translated back to a key code using the getKeyCode() method. This also offers a
way to get the name of the key assigned to a game action. For example, the help screen of an
application may display
"press "+getKeyName (getKeyCode (GAME_A))
instead of "press GAME_A".
The following canvas implementation shows the usage of the key event methods. For each key pressed,
repeated, or released, it shows the event type, character and code, key name, and game action.
The first part of the implementation stores the event type and code in two variables and schedules a
repaint whenever a key event occurs:
import javax.microedition.lcdui.*;
class KeyDemoCanvas extends Canvas {
String eventType = "- Press any!";
int keyCode;
public void keyPressed (int keyCode) {
eventType = "pressed";
this.keyCode = keyCode;
repaint();
}
public void keyReleased (int keyCode) {
eventType = "released";
this.keyCode = keyCode;
repaint();
}
public void keyRepeated (int keyCode) {
eventType = "repeated";
this.keyCode = keyCode;
repaint();
}
The second part prints all event properties available to the device screen. For this purpose, you first
implement an additional write() method that helps the paint() method to identify the current y
position on the screen. This is necessary because drawText() does not advance to a new line
automatically. The write() method draws the string at the given y position and returns the y position
plus the line height of the current font, so paint() knows where to draw the next line:
public int write (Graphics g, int y, String s) {
g.drawString (s, 0, y, Graphics.LEFT|Graphics.TOP);
Search WWH ::




Custom Search