J2ME 遊戲歡迎畫面後需顯示功能選單,主要有兩種路徑:
List 元件 — 開發快、跨裝置一致性好,但外觀受系統限制,自訂程度低Canvas 自繪 — 完全掌控繪圖細節,可實現動畫、特效、品牌化介面,主流遊戲採用Image.createImage("/res/menu.png")index 上下切換repaint() 觸發 paint(Graphics g) 重繪package welcomecanvas;
import javax.microedition.lcdui.*;
public class MainCanvas extends Canvas {
private Image background;
private int selectedIndex = 0; // 當前選中項目
private static final String[] ITEMS = {"新遊戲", "設定", "排行榜", "離開"};
public MainCanvas() {
try {
background = Image.createImage("/res/menu.png");
} catch (IOException e) {
// 載入失敗處理
}
}
protected void paint(Graphics g) {
// 1. 清屏
g.setColor(0xFFFFFF);
g.fillRect(0, 0, getWidth(), getHeight());
// 2. 繪製背景圖(置中)
if (background != null) {
int x = (getWidth() - background.getWidth()) / 2;
int y = (getHeight() - background.getHeight()) / 2;
g.drawImage(background, x, y, Graphics.TOP | Graphics.LEFT);
}
// 3. 繪製選單項目與選中高亮
Font font = Font.getDefaultFont();
int itemHeight = font.getHeight() + 10; // 含內距
int startY = (getHeight() - ITEMS.length * itemHeight) / 2;
for (int i = 0; i < ITEMS.length; i++) {
int y = startY + i * itemHeight;
int textX = (getWidth() - font.stringWidth(ITEMS[i])) / 2;
// 選中項目繪製高亮背景
if (i == selectedIndex) {
g.setColor(0x6699CC);
g.fillRect(textX - 10, y, font.stringWidth(ITEMS[i]) + 20, itemHeight);
g.setColor(0xFFFFFF); // 選中時字體白色
} else {
g.setColor(0x000000); // 普通黑色
}
g.drawString(ITEMS[i], textX, y + 5, Graphics.TOP | Graphics.LEFT);
}
}
protected void keyPressed(int keyCode) {
int action = getGameAction(keyCode);
switch (action) {
case Canvas.UP:
selectedIndex = (selectedIndex - 1 + ITEMS.length) % ITEMS.length;
break;
case Canvas.DOWN:
selectedIndex = (selectedIndex + 1) % ITEMS.length;
break;
case Canvas.FIRE: // 確認鍵
handleSelection(selectedIndex);
break;
}
repaint(); // 重繪
serviceRepaints(); // 立即刷新
}
private void handleSelection(int index) {
switch (index) {
case 0: startGame(); break;
case 1: showSettings(); break;
case 2: showHighScores(); break;
case 3: notifyDestroyed(); break;
}
}
// 業務邏輯佔位方法
private void startGame() { /* ... */ }
private void showSettings() { /* ... */ }
private void showHighScores() { /* ... */ }
}
| 技術點 | 說明 |
|---|---|
| 雙緩衝繪圖 | Canvas 預設支援雙緩衝,repaint() + serviceRepaints() 避免閃爍 |
| 按鍵映射 | 用 getGameAction(keyCode) 統一處理不同裝置按鍵碼差異 |
| 字體度量 | Font.stringWidth()、Font.getHeight() 計算版面配置 |
| 圖片資源 | 放置於 /res/ 目錄,JAR 打包時自動包含 |
| 生命週期 | showNotify()/hideNotify() 可處理顯示/隱藏時的資源載入釋放 |
pointerPressed())Manager.createPlayer())