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

J2ME 文本閱讀器實作完整教學:資源檔載入、Form 顯示、雙層選單導航

     編輯:J2ME

專案需求

  • 離線閱讀:文本打包於 JAR /res 目錄。
  • 分章節:每章一個 .txt,支援多段落、保留空白符號。
  • 兩級選單:主選單選章 → 內容頁閱讀 → 返回主選單。
  • 跨裝置相容:僅使用 MIDP 2.0 標準 API。

核心技術:資源檔讀取工具

private String readChapter(String resPath) {
    InputStream is = null;
    ByteArrayOutputStream bos = null;
    try {
        is = getClass().getResourceAsStream(resPath);
        bos = new ByteArrayOutputStream();
        int ch;
        while ((ch = is.read()) != -1) bos.write(ch);
        return bos.toString().trim();
    } catch (IOException e) {
        e.printStackTrace(); return "載入失敗:" + e.getMessage();
    } finally {
        try { if (is != null) is.close(); } catch (IOException ignored) {}
        try { if (bos != null) bos.close(); } catch (IOException ignored) {}
    }
}

主選單建構(List + 隱含選擇)

private List mainMenu;
private Command cmdExit = new Command("離開", Command.EXIT, 1);

private void showMainMenu() {
    mainMenu = new List("文本閱讀器", Choice.IMPLICIT);
    mainMenu.append("第一章", null);
    mainMenu.append("第二章", null);
    mainMenu.append("第三章", null);
    mainMenu.addCommand(cmdExit);
    mainMenu.setCommandListener(this);
    display.setCurrent(mainMenu);
}

內容頁顯示(Form + 返回命令)


private Command cmdBack = new Command("返回", Command.BACK, 1);

private void showChapter(int index) {
    String[] files = {"/res/ch1.txt","/res/ch2.txt","/res/ch3.txt"};
    String content = readChapter(files[index]);
    Form form = new Form("第 " + (index+1) + " 章");
    form.append(content);
    form.addCommand(cmdBack);
    form.setCommandListener(this);
    display.setCurrent(form);
}

統一事件處理


public void commandAction(Command c, Displayable d) {
    if (c == cmdExit) { destroyApp(false); notifyDestroyed(); }
    else if (c == cmdBack) { showMainMenu(); }
    else if (d == mainMenu) {
        showChapter(mainMenu.getSelectedIndex());
    }
}

完整 MIDlet 骨架

public class ReaderMIDlet extends MIDlet implements CommandListener {
    private Display display;
    // ... 欄位、建構子、startApp/pauseApp/destroyApp
    protected void startApp() { if (display == null) { display = Display.getDisplay(this); showMainMenu(); } }
    // commandAction 如上
}

進階擴展建議

  • 分頁顯示:長文本切割為多個 Form 或自訂 Canvas 畫頁碼。
  • 書籤/進度:RMS 記錄每章閱讀位置(字元偏移量)。
  • 字型調整:提供「大/中/小」三種字型切換,重新 form.append()。
  • 搜尋:String.indexOf() 關鍵字高亮(需 Canvas 繪製)。
  • 編碼支援:整合前文 GB2312→Unicode 轉換器,支援非 UTF-8 文本。

封裝與部署

  1. 專案結構:src/ReaderMIDlet.java、res/ch1.txt、res/ch2.txt、res/ch3.txt。
  2. WTK 專案設定資源目錄包含 res。
  3. 預驗證、混淆、簽名(如需 RMS 寫入權限)。

結語

以 List+Form 快速建構雙層導航,配合資源檔讀取工具,即可在數小時內完成功能完整的 J2ME 文本閱讀器,適合電子書、教材、說明書等離線閱讀場景。

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