Java Reference
In-Depth Information
Responding to Commands
By themselves, Command s aren't very exciting. They'll show up on the screen, but nothing happens
automatically when a user invokes a command. An object called a listener is notified when the
user invokes any command in a Displayable . This follows the basic form of the JavaBeans
event model; a Displayable is a unicast event source . A Displayable fires off an event every time
the user invokes one of its Command s.
The listener is an object that implements the CommandListener interface. To register the
listener with a Displayable , use the following method:
public void setListener(CommandListener l)
Displayable is a unicast event source because it can only have one listener object. ( Multicast
event sources can have multiple listeners and use an add... method for adding listeners rather
than a set... method.)
Implementing a CommandListener is a matter of defining a single method:
public void commandAction(Command c, Displayable s)
When a command is invoked, the Displayable that contains it calls the commandAction()
method of the registered listener.
Tip Event listeners should not perform lengthy processing inside the event-handling thread. The system
uses its own thread to call commandAction() in response to user input. If your implementation of
commandAction() does any heavy thinking, it will tie up the system's event-handling thread. If you have
anything complicated to do, use your own thread. Some JVM implementations may protect itself from what is
effectively a denial-of-service attack and terminate threads or applications that abuse system thread.
A Simple Example
By way of illustration, consider the following class:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Commander extends MIDlet {
public void startApp() {
Displayable d = new TextBox("TextBox", "Commander", 20, TextField.ANY);
Command c = new Command("Exit", Command.EXIT, 0);
d.addCommand(c);
d.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable s) {
notifyDestroyed();
}
} );
 
Search WWH ::




Custom Search