Saturday, July 25, 2009

Implementing CommandListener Interface in J2ME Applications

Classes that implement CommandListener interface, which has a single method: commandAction(Command com, Displayable dis), have the abilitiy to trace command click actions. In order to transfer command information to a listener, the listener is registered with the method setCommandListener(CommandListener listener). In the sample code at below, the command listener in this case is the form class itself which is implementing the commandAction() method.
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;

public class ConfirmationPopUpForm extends Form implements CommandListener {
 private Command cmdPreviousPage;
 private Command cmdExit; 
 public ConfirmationPopUpForm(){
  this("Confirmation Form");
 } 
 public ConfirmationPopUpForm(String title){
  super(title);  
  cmdPreviousPage = new Command("Return",Command.CANCEL, 0);
  addCommand(cmdPreviousPage);
  cmdExit = new Command("Exit",Command.OK, 1);
  addCommand(cmdExit);
  this.setCommandListener(this);
 }
 public void commandAction(Command cmd, Displayable display) {
  if(cmd == cmdExit){
   exitAction();
  }
  else if(cmd == cmdPreviousPage){
   showPreviousFormAction();
  }
 }
 private void showPreviousFormAction() {
  MainMenuForm.show();
 }
 private void exitAction() {
  StarterForm.show();
 } 
}

1 comment:

  1. nice short usage of CommandListener interface. Thanks!!

    ReplyDelete