在MyCanvas类中定义的最后一个方法是keyPressed()方法。当用户在键盘上按下一个按键时,设备的应用程序管理器会调用keyPressed()方法,把按键编码传给keyPressed()方法进行处理。 package mtk; import javax.microedition.lcdui.Canvas; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Graphics; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; public class KeyCodeExample extends MIDlet { private Display display; private MyCanvas canvas; public KeyCodeExample() { display=Display.getDisplay(this); canvas=new MyCanvas(this); } protected void destroyApp(boolean arg0){ } protected void pauseApp() { } public void exitMIDlet(){ destroyApp(true); notifyDestroyed(); } protected void startApp() throws MIDletStateChangeException { display.setCurrent(canvas); } } class MyCanvas extends Canvas implements CommandListener{ private final Command CMD_EXIT=new Command("退出",Command.EXIT,1); private String direction; private KeyCodeExample keyCodeExample; public MyCanvas(KeyCodeExample keyCodeExample){ direction="2=上 8=下 4=左 6=右"; this.keyCodeExample=keyCodeExample; addCommand(CMD_EXIT); setCommandListener(this); } protected void paint(Graphics graphics) { graphics.setColor(255,255,255); graphics.fillRect(0, 0, getWidth(), getHeight()); graphics.setColor(255,0,0); graphics.drawString(direction, 0, 0, Graphics.TOP|Graphics.LEFT); } public void commandAction(Command c, Displayable d) { if(c==CMD_EXIT){ keyCodeExample.exitMIDlet(); } } protected void keyPressed(int key){ switch(key){ case KEY_NUM2: direction="上"; break; case KEY_NUM4: direction="左"; break; case KEY_NUM6: direction="右"; break; case KEY_NUM8: direction="下"; break; } repaint(); } }