protected void paint(Graphics g) {
// 系統自動呼叫,g 為系統提供的繪圖上下文
// 所有繪圖操作必須在這裡或衍生呼叫中進行
}
觸發機制:呼叫 repaint() → 系統排程 → 呼叫 paint(g)。
為了在 run() 迴路中也能繪圖 (非 paint 內),需保存系統傳入的 Graphics:
static Graphics ourGraphics = null;
protected void paint(Graphics g) {
if (ourGraphics == null) ourGraphics = g; // 僅首次賦值
// 後續可在任何地方用 ourGraphics 繪圖
}
注意:repaint() 後系統呼叫 paint() 可能有延遲,使用前務必檢查 ourGraphics != null。
static int gameState = 0;
static int temp = 0;
public void run() {
while (true) {
switch (gameState) {
case 0:
repaint(); // 觸發 paint 取得 ourGraphics
gameState = 1; // 下一幀進入狀態 1
break;
case 1:
if (ourGraphics == null) break; // 尚未就緒
ourGraphics.setColor(0x000000);
ourGraphics.fillRect(0, 0, 128, 128);
ourGraphics.setColor(0x00FF00);
ourGraphics.fillRect(20, 20, 88, 88);
if (++temp == 1000) gameState = 2; // 1000 幀後切換
break;
case 2:
ourGraphics.setColor(0x000000);
ourGraphics.fillRect(0, 0, 128, 128);
ourGraphics.setColor(0xFFFFFF);
ourGraphics.drawString("Fuck Man! It's New Game!",
128 >> 1, 128 >> 1, Graphics.TOP | Graphics.HCENTER);
// 保持狀態 2 不變,持續顯示文字
break;
}
repaint(); // 關鍵:將 ourGraphics 繪製內容刷新到螢幕
// 建議加上幀率控制 sleep (見教學二)
}
}
優點:繪圖與狀態邏輯集中,避免 ourGraphics 同步問題,結構更清晰。
public void run() {
while (true) {
repaint(); // 唯一工作:觸發重繪
// 幀率控制 sleep...
}
}
protected void paint(Graphics g) {
if (ourGraphics == null) ourGraphics = g;
switch (gameState) {
case 0:
repaint(); gameState = 1; break;
case 1:
if (ourGraphics == null) return;
ourGraphics.setColor(0x000000);
ourGraphics.fillRect(0, 0, 128, 128);
ourGraphics.setColor(0x00FF00);
ourGraphics.fillRect(20, 20, 88, 88);
if (++temp == 1000) gameState = 2;
break;
case 2:
ourGraphics.setColor(0x000000);
ourGraphics.fillRect(0, 0, 128, 128);
ourGraphics.setColor(0xFFFFFF);
ourGraphics.drawString("Fuck Man! It's New Game!",
128 >> 1, 128 >> 1, Graphics.TOP | Graphics.HCENTER);
break;
}
// paint 結束即自動呈現,無需額外 repaint()
}
0xRRGGBB,如 0xFF0000 紅、0x00FF00 綠、0x0000FF 藍。可用 Photoshop 取色器取得。128 >> 1 等同 128 / 2 (64),J2ME 常用位移優化除法。Graphics.TOP | Graphics.HCENTER 置中對齊。docs/api/midp/index.html → 點 Index → 字母索引查找 (如 G 找 Graphics)。熟練查閱 Graphics、Image、Canvas 方法簽章與參數說明,是高效開發關鍵。
動畫系統:幀陣列管理、播放速度控制、模組化合成 (頭/身/肢體分離)、碰撞檢測與模組概念。