一个电话日历应用程序 // Import of API classes import javax.microedition.midlet.*;
import javax.microedition.lcdui.*; import java.util.*; //A first MIDlet with simple text and a few commands. public class PhoneCalendar extends MIDlet implements CommandListener, ItemStateListener { //The commandsprivate Command exitCommand; //The display for this MIDletprivate Display display; // Display items e.g Form and DateFieldForm displayForm; DateField date; public PhoneCalendar() { display = Display.getDisplay(this); exitCommand = new Command("Exit", Command.SCREEN, 1); date = new DateField("Select to date", DateField.DATE); } // Start the MIDlet by creating the Form and // associating the exit command and listener. public void startApp() { displayForm = new Form("Quick Calendar"); displayForm.append(date); displayForm.addCommand(exitCommand); displayForm.setCommandListener(this); displayForm.setItemStateListener(this); display.setCurrent(displayForm);
} public void itemStateChanged(Item item) { // Get the values from changed item } // Pause is a no-op when there is no background // activities or record stores to be closed. public void pauseApp() { } // Destroy must cleanup everything not handled // by the garbage collector. public void destroyApp (boolean unconditional) { } // Respond to commands. Here we are only implementing // the exit command. In the exit command, cleanup and // notify that the MIDlet has been destroyed. public void commandAction (Command c, Displayable s) { if (c == exitCommand) { destroyApp(false); notifyDestroyed(); } } } 如上定义的 PhoneCalendar MIDlet 继承了 ItemListener 和 CommandListener。它使 MIDlet 具备了跟踪屏幕上的条目变化和对用户命令作出响应的功能。由此应用程序创建的用户界面从为电话屏幕定义一个显示并附加上一个 Form 开始。该 Form 充当容器使用,可以保持一些用户界面项。commandAction() 函数在 J2ME 中执行命令处理程序,并且定义某个命令应执行的动作。
部署 J2ME 您可以从 Sun 下载一个仿真器,该仿真器允许您在台式机系统上测试 J2ME 应用程序。如果您宁愿避免所有的图形开销,则您也可以在命令行上部署 J2ME。