MIDP UI 分為高階 (High-level) 與低階 兩套體系。本文詳細說明核心類別架構、Graphics/Canvas 繪圖機制,並以「SaveMyMoney 銀行選單」完整實作示範 List、TextBox、Gauge、命令導航與畫面切換。
javax.microedition.lcdui。Displayable (GUI 輸出) → 衍生 Screen (高階) 與 Canvas (低階)。Form、List、TextBox、Alert、TextField、Gauge、Ticker — 具裝置適配能力,自動處理佈局。Canvas、Graphics — 開發者完全控制繪圖、按鍵、遊戲迴圈。Graphics:提供 2D 幾何繪圖、文字、影像渲染方法。不直接建立,由 Canvas.paint(Graphics g) 回呼傳入。Canvas:低階繪圖畫布,覆寫 paint()、keyPressed() 等實現自定義互動。Screen:高階 UI 基類,衍生 Form、List、TextBox、Alert。class TestCanvas extends Canvas {
public void paint(Graphics g) {
Font font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
g.setFont(font);
g.drawString("Hello MIDP", getWidth()/2, getHeight()/2, Graphics.HCENTER | Graphics.TOP);
try {
Image img = Image.createImage("/myimage.png");
g.drawImage(img, 0, 0, Graphics.HCENTER | Graphics.TOP);
} catch (Exception e) {}
}
}
List:餘額查詢、定存查詢、支票狀態。Gauge 進度指示器 (Form)。TextBox 輸入支票號 → 再顯示進度指示器。public class MidpGui extends MIDlet implements CommandListener {
private Display display;
private Form form = new Form("Container Form");
private List menu;
private TextBox input;
private Gauge gauge = new Gauge("Processing...", false, 100, 30);
private static final Command okCmd = new Command("OK", Command.OK, 1);
private static final Command backCmd = new Command("Back", Command.BACK, 0);
private static final Command exitCmd = new Command("Exit", Command.STOP, 2);
private String currentMenu;
public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
menu = new List("Enquiries", Choice.IMPLICIT);
menu.append("Current Balance", null);
menu.append("Fixed Deposit", null);
menu.append("Check Status", null);
menu.addCommand(exitCmd);
menu.setCommandListener(this);
mainMenu();
form.append(gauge);
}
void mainMenu() { display.setCurrent(menu); currentMenu = "Main"; }
public void showTextBox() {
input = new TextBox("Enter Check Number:", "", 20, TextField.ANY);
input.addCommand(backCmd); input.addCommand(okCmd);
input.setCommandListener(this); input.setString("");
display.setCurrent(input); currentMenu = "input";
}
public void showForm() {
form.addCommand(backCmd); form.setCommandListener(this);
display.setCurrent(form); currentMenu = "form";
}
public void commandAction(Command c, Displayable d) {
String lbl = c.getLabel();
if ("Exit".equals(lbl)) { destroyApp(true); }
else if ("Back".equals(lbl)) { mainMenu(); }
else if ("OK".equals(lbl)) {
if ("Main".equals(currentMenu)) {
String sel = menu.getString(menu.getSelectedIndex());
if (sel.startsWith("Current") || sel.startsWith("Fixed")) showForm();
else if (sel.startsWith("Check")) showTextBox();
} else if ("input".equals(currentMenu)) { showForm(); }
}
}
// pauseApp/destroyApp 釋放參考...
}
Canvas + Graphics。Canvas 亦可加入 Command 與 Ticker。