下面的代码介绍了如何使用Alert来创建一个确认对话框。
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class ConfirmationMIDlet extends MIDlet implements CommandListener { private Form form; private Alert alert; private Command exitCommand; public void startApp() { form = new Form("ConfirmationMIDlet"); exitCommand = new Command("Exit", Command.EXIT, 1); form.setCommandListener(this); form.addCommand(exitCommand); Display.getDisplay(this).setCurrent(form); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void commandAction(Command c, Displayable d) { if (c == exitCommand) { showConfirmation("Confirmation", "Do you really want to exit?"); } } private void closeAlert() { Display.getDisplay(this).setCurrent(form); alert = null; } protected void showConfirmation(String title, String text) { alert = new Alert(title, text, null, AlertType.CONFIRMATION); alert.addCommand(new Command("Yes", Command.OK, 1)); alert.addCommand(new Command("No", Command.CANCEL, 1)); alert.setCommandListener(new CommandListener() { public void commandAction(Command c, Displayable d) { if (c.getLabel().equals("Yes")) { notifyDestroyed(); } if (c.getLabel().equals("No")) { closeAlert(); } } }); Display.getDisplay(this).setCurrent(alert, form); } }