Java ME and the Command Pattern
by Darius Katz

Listing One

public void commandAction(Command command, Displayable d) {
   if (command == firstCommand) {
      textBox.setString("First command executed");
   } else if (command == secondCommand) {
      textBox.setString("Second command run");
   } else if (command == thirdCommand) {
      textBox.setString("Third command chosen");
   } else if (command == exitCommand) {
      notifyDestroyed();
   }
}


Listing Two

(a)
// Implementation of the CommandListener
public void commandAction(Command command, Displayable d){
   AbstractCommand abstractCommand = (AbstractCommand)command;
   abstractCommand.execute();
}

(b)

public abstract class AbstractCommand extends Command {
   public AbstractCommand(String label, int commandType, int priority) {
      super(label, commandType, priority);
   }
   /* This is where the action goes. */
   public abstract void execute();
}

Listing Three 

public class MyCommand extends AbstractCommand {
   private TextBox textBox;
   public MyCommand(TextBox t){
      super("Simsalabim", Command.SCREEN, 2);
      textBox = t;
   }
   /* This is where the action is. */
   public void execute() {
      textBox.setString("A rabbit appears");
   }
}

Listing Four

(a)
public void startApp() {
   display = Display.getDisplay(this);
   textbox = new TextBox("Command magic", "Do your magic...", 256, 
      TextField.ANY);
   //Prepare commands
   textbox.addCommand(new ExitCommand(this));
   textbox.addCommand(new MyCommand(textbox));
   textbox.addCommand(new AnotherCommand(textbox));
   textbox.addCommand(new YetAnotherCommand(textbox));
   textbox.setCommandListener(this);
   display.setCurrent(textbox);
}

(b)

public class ExitCommand extends AbstractCommand {
   private MIDlet midlet;
   public ExitCommand(MIDlet m) {
      super("Exit", Command.EXIT, 2);
      midlet = m;
   }
   /* This is where the action is. */
   public void execute() {
      midlet.notifyDestroyed();
   }
}


Listing Five

(a)

class CommandExecuter implements Runnable {
   private AbstractCommand command;
   public CommandExecuter(AbstractCommand c) {
      command = c;
   }
   public void run() {
      command.execute();
   }
}

(b) 

// Implementation of CommandListener
public void commandAction(Command command, Displayable d){
   Runnable execute =
      new CommandExecuter((AbstractCommand)command);
   new Thread(execute).start();
}


2


