Adding Commands
Any MIDlet, in order to be useful, will need to accept some form of input from the user. In this article, we will look at a common form of input for MIDlets, commands. We’ll also create a sample MIDlet that responds to the corresponding events.
One of the simplest ways for a MIDlet to accept input is through commands. Simply put, a command represents a specific action that can be performed by the MIDlet. How commands are presented to the user will depend on the implementation. On most cell phones, they are mapped to the two buttons directly below the LCD. If there are more than two commands, one of the buttons will bring up a menu with the remaining commands. At the very least, you will probably want to add an exit command to your application.
Going back to our last demo application, lets add an exit command. First, modify the MIDlet class to implement the CommandListener interface.
public class DemoMidlet extends MIDlet
implements CommandListener {
Next, add an instance variable to the MIDlet class to represent the the exit Command object.
private Command exit;
After that, add code to the startApp() method to add the command to the canvas, and set the MIDlet class as a command listener.
public void startApp() {</p><p> Display display = Display.getDisplay(this); // Get display
canvas = new MyCanvas(); // Create instance of canvas</p><p> // Add exit command to canvas
exit = new Command("Exit", Command.EXIT, 1);
canvas.addCommand(exit);
canvas.setCommandListener(this);</p><p> // Set our canvas as the current displayable object
display.setCurrent(canvas); </p><p> // Start main thread
canvas.state = MyCanvas.STATE_RUNNING;
new Thread(canvas).start();</p><p>}
Lastly, add a the required handler for the command action.
public void commandAction(Command command, Displayable screen) {</p><p> if (command == exit) {
destroyApp(false); // Allow MIDlet to release resources
notifyDestroyed(); // Signal platform to destroy MIDlet
}</p><p>}
The code in our event handler simply destroys the application. If you had more than one command, you could simply create more if statements within the commandAction() method.
The complete source code for the project described in this tutorial can be downloaded here: Source Code
Bookmark this article: del.icio.us Digg Furl Reddit blogmarks Google Spurl StumbleUpon Technorati Yahoo!