import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Graphics;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;


public class LLEventMIDlet extends MIDlet
{
private Display display;


public LLEventMIDlet()
{
super();
display = Display.getDisplay(this);
// TODO Auto-generated constructor stub
}


protected void startApp() throws MIDletStateChangeException
{
// TODO Auto-generated method stub
MyCanvas mc = new MyCanvas();
display.setCurrent(mc);
}


protected void pauseApp()
{
// TODO Auto-generated method stub

}


protected void destroyApp(boolean arg0) throws MIDletStateChangeException
{
// TODO Auto-generated method stub

}


private class MyCanvas extends Canvas
{
String action = "";


public void paint(Graphics g)
{
g.setColor(255, 255, 255);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(0, 0, 0);

if (hasRepeatEvents())
{
g.drawString("Repeat", 10, 10, 0);

} else
{
g.drawString("NonRepeat", 10, 10, 0);
}
g.drawString(action, 10, 20, 0);
}

protected void keyPressed(int keyCode)
{
action = "KP: " + (char)keyCode;
repaint();
}

protected void keyReleased(int keyCode)
{
action = "KR: " + (char)keyCode;
repaint();
}

protected void keyRepeated(int keyCode)
{
action = "KRe: " + (char)keyCode;
repaint();
}
}

}

在MIDP 1.0 規格中,Canvas 類別裡頭定義了幾個常數,他們分
別是: KEY_NUM0 、KEY_NUM1 、KEY_NUM2 、KEY_NUM3 、KEY_NUM4 、KEY_NUM5 、KEY_NUM6 、KEY_NUM7 、KEY_ NUM8 、KEY_NUM9 、KEY_STAR、KEY_POUND 共11 個,分別代表0~9 的數字鍵、星號鍵、以及井號鍵。我們可以利用這幾個常數判定鍵盤(按鈕)事件處理函式所傳進來的keyCode,藉以了解哪個按鈕被按下了,當然,除了這些按鍵之外,其他的按鍵也會有其對應值,您必須自己嘗試找出來,但是為了可以跨平台,建議您僅只使用這些標準的定義鍵。
為了Game 設計師的方便,MIDP 1.0 規格中,Canvas 類別裡頭定義了幾個與Game 鍵盤代碼相關的常數,他們分別是UP、DOWN、LEFT、RIGHT、FIRE、GAME_A、GAME_B、GAME_C、GAME_D。這些定義雖然很可能會和之前的定義有所重複,但是因為有了一層抽象性,在移植的時候也就方便多了。
那麼,在程式裡頭該如何處理呢? Canvas 裡頭提供了兩個函式:
1. getGameAction() 傳入keyCode,函式會回傳所代表的
Game 鍵盤代碼。
用法如下:
public void keyPressed(int keyCode)


{
switch(getGameAction(keyCode))


{
case Canvas.LEFT:
moveLeft() ;
break ;
case Canvas.FIRE:
fire() ;
break ;

略
}
} 2. getKeyCode() 傳入Game 鍵盤代碼,函式會回傳所代表的
keyCode。
用法如下:
public void keyPressed(int keyCode)


{
if(keyCode == getKeyCode(Canvas.LEFT))


{
moveLeft() ;
}else if(keyCode == getKeyCode(Canvas.FIRE))


{
fire() ;
}

略
} 任選任何一種方法,都可以達到跨平台的目的。