Handling Key Events
Java ME supports several input mechanisms. In a previous tutorial, we looked at the high-level commands as a means of accepting input from the user. This time, we will look at low-level key events, which are handled through the keyPressed() and keyReleased() methods. We will also look at how to use these methods in a highly interactive game or application.
When the user presses a key, the application is notified by calling the keyPressed() method of the Canvas object. Similarly, when a key is released, keyReleased() is called. These methods are passed a key code which maps to the Unicode encoding of the corresponding character. Whenever possible, you should refer to the key codes using their defined constants:
Canvas.KEY_NUM0Canvas.KEY_NUM1Canvas.KEY_NUM2Canvas.KEY_NUM3Canvas.KEY_NUM4Canvas.KEY_NUM5Canvas.KEY_NUM6Canvas.KEY_NUM7Canvas.KEY_NUM8Canvas.KEY_NUM9Canvas.KEY_STARCanvas.KEY_POUND
Additionally, MIDP provides a device independent means of mapping keys to actions which are normally associated with video games. An application can translate a key code to the corresponding game action with the getGameAction(). The available game actions are:
Canvas.UPCanvas.DOWNCanvas.LEFTCanvas.RIGHTCanvas.FIRECanvas.GAME_ACanvas.GAME_BCanvas.GAME_CCanvas.GAME_D
If you are targeting the MIDP 2.0 platform and are using a GameCanvas object, you can also take advantage of the GameCanvas.getKeyStates() method. The getKeyStates() method returns a bit mask describing which keys are being held down or have been pressed since the last call. This method is useful when your game logic is running in a custom thread. In such cases, you don’t want to directly respond to the key events asynchronously in the keyPressed() method, as this could cause undesirable side-effects. Instead, you should check the key states in the main loop of the custom thread, and respond to key presses there.
In MIDP 1.0, similar functionality can be implemented by setting your own bit masks in the keyPressed() method, and clearing them in the keyReleased() method. Here is some example code that keeps track of what game action keys are currently being held down:
private static int gameActionDownMask;
public void keyPressed(int keyCode) {
int gameAction = getGameAction(keyCode);
gameActionDownMask
= gameActionDownMask | ( 1 << gameAction );
}
public void keyReleased(int keyCode) {
int gameAction = getGameAction(keyCode);
gameActionDownMask
= gameActionDownMask & ( ~( 1 << gameAction ) );
}
public static final boolean isGameActionTrue(int gameAction) {
return ( gameActionDownMask & ( 1 << gameAction ) ) != 0;
}
Bookmark this article: del.icio.us Digg Furl Reddit blogmarks Google Spurl StumbleUpon Technorati Yahoo!