So now that we've talked about MIDlets a little, talk about their components a little. Other than MIDlet, we use three key elements- Form, Command, and CommandListener. The Form class is an important container in Java ME, with the ability to contain images, text fields, date fields, gauges, choice groups, and custom items. The Command class is used like Events from javax.swing in Java SE. The CommandListener interface is then used to "listen" for Commands and execute appropriate actions, just like in the Java SE Swing Model.
So now that we have an idea of what tools we are working with, let's examine a Hello, World MIDlet.
//contains User Interface tools for MIDlets
import javax.microedition.lcdui.*;
//contains MIDlet and MIDletStateChangeException
import javax.microedition.midlet.*;
public class MyMidlet extends MIDlet implements CommandListener{
private Form display;
private Command pause, exit;
public MyMidlet(){
//sets a title for the Form
display = new Form("My First Midlet");
//Command(label, type, priority)
//note that the type constants are more for
//the developer's benefit than anything else
//the actions are all defined by the CommandListener
pause = new Command("Back", Command.BACK, 2);
exit = new Command("Destroy MIDlet", Command.EXIT, 1);
display.setCommandListener(this);
display.addCommand(pause);
display.addCommand(exit);
//have the Form display my message
display.append("Hello, World MIDlet!");
}
//in this MIDlet, the little logic we do have is
//handled by the CommandListener
public void startApp(){
Display.getDisplay(this).setCurrent(display);
}
//this method handles the Paused state
//the notifyPaused() method tells the MIDlet to enter
//the paused state. It has no effect if the MIDlet
//has not been started or has been destroyed
public void pauseApp(){
this.notifyPaused();
}
/*
@param unconditional- used to tell the destroyApp() method whether
or not to destroy the MIDlet.
*/
public void destroyApp(boolean unconditional){
this.notifyDestroyed(); //destroy the MIDlet
}
//this is the CommandListener method
//note that I use the == operator to compare Commands
//as I only want one copy of a particular Command able to
//trigger an event, not equal Commands in terms of attributes
public void commandAction(Command c, Displayable d) {
if(c == pause) pauseApp();
else if(c == exit) destroyApp();
}
}







MultiQuote


|