MIDP GUI 分為高階(Form、List、TextBox)與低階(Canvas、Graphics)。高階易用、跨平台一致,但外觀受系統控制;低階掌控力強、可自訂繪圖邏輯,適合遊戲選單、特效介面。
x = (螢幕寬 - 選單寬) / 2、y = (螢幕高 - 選單高) / 2int selected 記錄當前選中索引keyPressed() 判斷方向鍵,更新 selected 並 repaint()selected 繪製高亮背景package com.j2medev.chapter3;
import javax.microedition.lcdui.*;
public class MenuCanvas extends Canvas {
private int selected = 0;
private int preferWidth = -1;
private int preferHeight = -1;
public static final String[] LABELS = {"新遊戲", "設定", "排行榜", "離開"};
public MenuCanvas() {
// 建構子計算項目尺寸
Font font = Font.getDefaultFont();
for (String label : LABELS) {
int w = font.stringWidth(label);
if (w > preferWidth) preferWidth = w;
}
preferWidth += 16; // 左右各 8px 內距
preferHeight = font.getHeight() + 8; // 上下各 4px 內距
}
protected void paint(Graphics g) {
// 保存原顏色
int oldColor = g.getColor();
// 清屏
g.setColor(0xFFFFFF);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(oldColor);
// 計算選單矩形區域
int rectWidth = preferWidth;
int rectHeight = preferHeight * LABELS.length;
int x = (getWidth() - rectWidth) / 2;
int y = (getHeight() - rectHeight) / 2;
// 繪製外框與分隔線
g.drawRect(x, y, rectWidth, rectHeight);
for (int i = 1; i < LABELS.length; i++) {
g.drawLine(x, y + preferHeight * i, x + rectWidth, y + preferHeight * i);
}
// 繪製項目文字與高亮
for (int j = 0; j < LABELS.length; j++) {
int itemY = y + j * preferHeight;
if (selected == j) {
// 高亮背景
g.setColor(0x6699CC);
g.fillRect(x + 1, itemY + 1, rectWidth - 1, preferHeight - 1);
g.setColor(oldColor);
}
// 文字置中偏左繪製
g.drawString(LABELS[j], x + 8, itemY + 4, Graphics.LEFT | Graphics.TOP);
}
}
protected void keyPressed(int keyCode) {
int action = getGameAction(keyCode);
switch (action) {
case Canvas.FIRE:
handleSelection(selected);
break;
case Canvas.DOWN:
selected = (selected + 1) % LABELS.length;
break;
case Canvas.UP:
selected = (selected - 1 + LABELS.length) % LABELS.length;
break;
}
repaint();
serviceRepaints(); // 立即刷新
}
private void handleSelection(int index) {
System.out.println("選擇: " + LABELS[index]);
// 實際專案中轉場至對應畫面
}
protected void showNotify() {
System.out.println("showNotify() called");
}
}
| 方法/類別 | 用途 |
|---|---|
Canvas.getGameAction(keyCode) | 將裝置特定鍵碼映射為標準遊戲動作(UP、DOWN、FIRE 等) |
Graphics.drawString(str, x, y, anchor) | 繪製文字,anchor 參數控制對齊(LEFT/TOP/HCENTER/VCENTER 等) |
Font.stringWidth(str) | 取得字串像素寬度,用於版面計算 |
repaint() / serviceRepaints() | 請求重繪 / 立即執行待處理重繪(雙緩衝) |
showNotify() / hideNotify() | Canvas 顯示/隱藏時回調,適合載入/釋放資源 |
pointerPressed(x, y) 判斷點擊區域showNotify() 載入