Add Command to MIDlet : Command « J2ME « Java Tutorial






import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.Ticker;
import javax.microedition.midlet.MIDlet;

public class TextBoxMIDlet extends MIDlet implements CommandListener {
  private static final int MAX_TEXT_SIZE = 64;
  protected TextBox textBox;
  protected Display display;
  private static final Command EXIT_COMMAND = new Command("Exit", Command.EXIT,0);

  private static final Command OK_COMMAND = new Command("OK", Command.OK, 0);

  private static final Command CLEAR_COMMAND = new Command("Clear",Command.SCREEN, 1);

  private static final Command REVERSE_COMMAND = new Command("Reverse",Command.SCREEN, 1);

  protected void startApp() {
    String str = null;
    try {
      InputStream is = getClass().getResourceAsStream("resources/text.txt");
      InputStreamReader r = new InputStreamReader(is);
      char[] buffer = new char[32];
      StringBuffer sb = new StringBuffer();
      int count;
      while ((count = r.read(buffer, 0, buffer.length)) > -1) {
        sb.append(buffer, 0, count);
      }
      str = sb.toString();
    } catch (IOException ex) {
      str = "Failed to load text";
    }
    textBox = new TextBox("TextBox Example", str, MAX_TEXT_SIZE, TextField.ANY);
    Ticker ticker = new Ticker("This is a ticker...");
    textBox.setTicker(ticker);
    textBox.addCommand(OK_COMMAND);
    textBox.addCommand(EXIT_COMMAND);
    textBox.addCommand(CLEAR_COMMAND);
    textBox.addCommand(REVERSE_COMMAND);
    textBox.setCommandListener(this);
    display = Display.getDisplay(this);
    display.setCurrent(textBox);
  }

  protected void pauseApp() {
  }

  protected void destroyApp(boolean unconditional) {
  }

  public void commandAction(Command c, Displayable d) {
    if (c == EXIT_COMMAND) {
      destroyApp(true);
      notifyDestroyed();
    } else if (c == OK_COMMAND) {
      System.out.println("OK pressed");
    } else if (c == CLEAR_COMMAND) {
      textBox.setString(null);
    } else if (c == REVERSE_COMMAND) {
      String str = textBox.getString();
      if (str != null) {
        StringBuffer sb = new StringBuffer(str);
        textBox.setString(sb.reverse().toString());
      }
    }
  }
}








31.17.Command
31.17.1.Add Command to MIDlet
31.17.2.Start the MIDlet by creating a list of items and associating the exit command with itStart the MIDlet by creating a list of items and associating the exit command with it
31.17.3.A MIDlet with simple text and a few commands.
31.17.4.Get command label and typeGet command label and type
31.17.5.Exit Command
31.17.6.Help commandHelp command