手把手教學在 NetBeans IDE 4.0 + Mobility Pack 4.0 建立 J2ME 專案,撰寫第一個 MIDlet 並顯示圖片驗證資源路徑。
HuaRongDao,主目錄任意,取消「Create HelloMIDlet」public class HuaRongDaoMidlet extends MIDlet implements CommandListener {
private Display display;
private static final Command CMD_EXIT = new Command("退出", Command.EXIT, 1);
public HuaRongDaoMidlet() { display = Display.getDisplay(this); }
protected void startApp() {
TextBox t = new TextBox("標題", "內容", 256, 0);
t.addCommand(CMD_EXIT);
t.setCommandListener(this);
display.setCurrent(t);
}
protected void pauseApp() {}
protected void destroyApp(boolean u) {}
public void commandAction(Command c, Displayable d) {
if (c == CMD_EXIT) { destroyApp(false); notifyDestroyed(); }
}
}
protected void startApp() {
Form form = new Form("測試頁");
try {
Image img = Image.createImage("/Duke.png"); // 相對專案根目錄 /res/
form.append(new ImageItem("Duke", img, ImageItem.LAYOUT_DEFAULT, "無法顯示"));
} catch (IOException e) { /* 忽略 */ }
form.addCommand(CMD_EXIT);
form.setCommandListener(this);
display.setCurrent(form);
}
關鍵:若圖片不顯示,專案屬性 → Libraries & Resources → 加入 res 完整路徑。NetBeans 編譯時會將 /res 內容打包進 JAR,createImage("/Duke.png") 即可載入。
環境就緒,下一步進入核心遊戲模組開發(見下篇)。