首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

J2ME 入門實戰(三):Gauge 組件互動演示

     編輯:Java 相關知識

代碼結構

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」退出程式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved