Home > Articles > Programming > Java

  • Print
  • + Share This
From the author of

Command Objects

A Command object is an object that holds information about an event. The simplest way to think of a Command is as a "button", something that you press or select. Figure 1 shows a Command with the label Exit. This Command is associated with the button directly below it on the device, often referred to as a soft button. This idea that a Command is a button is a good starting point. However, because of limited screen space and the differences in availability of buttons on a device, it's not always that simple. We will explore this further as we delve into this article.

A few steps are required before we can process events:

  1. Create a Command object to hold information about an event.

  2. Add the Command to a Form, Textbox, List, or Canvas.

  3. Add an event listener to the previous component.

When an event is triggered, the method commandAction() will be called. Within this method, you can determine what command initiated the action and process the event accordingly. Here are a few lines of code that show the basics:

private Form fmMain;      // Main form   
private Command cmExit;     // Command to exit the MIDlet
fmMain = new Form("Core J2ME");    // Form object
cmExit = new Command("Exit", Command.EXIT, 1); // Command object
fmMain.addCommand(cmExit);      // Add Command to Form
fmMain.setCommandListener(this);   // Listen for Form events


public void commandAction(Command c, Displayable s)
 // Exit the MIDlet
 if (c == cmExit)  
  • + Share This
  • 🔖 Save To Your Account