O'Reilly logo

J2ME in a Nutshell by Kim Topley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Event Handling

So far, you have seen how to use the Canvas, Image, and Graphics classes to draw lines, shapes, and images onto the screen. The low-level API also provides the ability for a MIDlet to detect and respond to user input from the keypad and a pointing device, if the device has one.

Key Handling

High-level API user interface components like TextBox and TextField automatically handle interaction with the user via the keypad (or its equivalent), so that the MIDlet just has to wait for the user to indicate that input is complete and read the content of the control as a String or an array of characters. If you are using the low-level API, however, the only way to respond to keyboard input is by overriding the following methods of the Canvas class:

protected void keyPressed(int keyCode)
protected void keyReleased(int keyCode)
protected void keyRepeated(int keyCode)

The keyPressed( ) and keyReleased( ) methods are, fairly obviously, called when the user presses and releases a key. If the user holds a key down for a device-dependent time, some platforms periodically call the keyRepeated( ) method, passing it the same argument as that supplied to the previous keyPressed( ) call. Since not all devices have a repeating keyboard, a MIDlet can determine whether to expect these events by calling the Canvas hasRepeatEvents( ) method and adjusting its behavior appropriately.

Unlike PC keyboards, which are more or less standardized, the wide range of different devices supported by MIDP ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required