public class GaugeMIDlet extends MIDlet implements CommandListener {
private Gauge gauge;
private Form form;
private Command exitCmd, okCmd;
private Display display;
private Alert alert;
public GaugeMIDlet() {
form = new Form("GaugeTest");
exitCmd = new Command("EXIT", Command.EXIT, 1);
okCmd = new Command("OK", Command.OK, 1);
gauge = new Gauge("Progress", true, 100, 50); // 互動式、最大100、初始50
alert = new Alert("Value", null, null, AlertType.INFO);
form.addCommand(exitCmd); form.addCommand(okCmd);
form.append(gauge); form.setCommandListener(this);
}
protected void startApp() {
display = Display.getDisplay(this);
display.setCurrent(form);
}
protected void pauseApp() {}
protected void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable d) {
if (c == exitCmd) { destroyApp(false); notifyDestroyed(); }
else if (c == okCmd) {
int val = gauge.getValue();
alert.setString("The Value is " + val);
display.setCurrent(alert, form);
}
}
}
Gauge(boolean interactive, int max, int initial):interactive=true 允許用戶左右鍵調整值;false 則為進度條模式。CommandListener 處理軟鍵事件,Display.setCurrent(Alert, nextDisplayable) 實現 Alert 彈出後自動返回 Form。MIDlet 生命週期三方法:startApp/pauseApp/destroyApp。模擬器中顯示可拖動滑塊的 Gauge,按「OK」彈出當前數值 Alert,按「EXIT」退出程式。