Use a command with one UI component

You can define a command for use with one UI component in your BlackBerry® device application. Using this approach, you don't need to define metadata for the command. The core UI components for BlackBerry device applications that support commands include menu items, buttons, pop-up menu items, and toolbars.
  1. Import the required classes and interfaces.
    import net.rim.device.api.command.*;
    import net.rim.device.api.ui.*;
    import net.rim.device.api.ui.container.*;
  2. Create a command handler by creating a class that extends the abstract CommandHandler class. In execute(), define the functionality that you want to associate with the UI component. To specify whether a command is executable for a given context object, you can implement a canExecute() method in your command handler. If you don't implement canExecute(), your command is always executable.
    // this command is always executable
    class DialogCommandHandler extends CommandHandler
       public void execute(ReadOnlyCommandMetadata metadata, Object context)
          Dialog.alert("Executing command for " + context.toString());
  3. Create the UI component.
    MenuItem myItem = new MenuItem(new StringProvider("My Menu Item"), 
       0x230000, 0);
  4. For a menu item or button, you can optionally set the context for the command using the UI component's setCommandContext() method. For some commands, a context might be needed to determine what the command should do. If you don't set a context, the menu item object or button object is the context.
    myItem.setCommandContext(new Object()
       public String toString()
          return "My MenuItem Object"; 
  5. Invoke setCommand() to specify the command for the UI component and provide the command handler as the method's argument.
    myItem.setCommand(new Command(new DialogCommandHandler()));
  6. Add the component to your screen.
The command is executed when a BlackBerry device user performs an action on the UI component (for example, when the user clicks a menu item).

Code samples

For examples of this approach to defining and using commands, see the API reference for MenuItem and ButtonField.

Previous topic: Command Framework API

Was this information helpful? Send us your comments.