KeyCode.java(第一个文件) import javax.microedition.midlet.*; import javax.microedition.lcdui.*; //import MyCanvas.java; public class KeyCode extends MIDlet { private Display display; private MyCanvas canvas; //定义canvas属性,引用的是用户自定义类 //MyCanvas canvas = new canvas(); public KeyCode() { display = Display.getDisplay(this); canvas = new MyCanvas(this);//实例化canvas } protected void startApp() { display.setCurrent(canvas);//当程序启动时将canvas注册到程序中 } protected void pauseApp() { } protected void destroyApp( boolean unconditional ) { } public void exitMIDlet()//退出方法 { destroyApp(true); notifyDestroyed(); } } MyCanvas.java(第二个文件) import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class MyCanvas extends Canvas implements CommandListener { private Command exit; private String direction;//定义String型方向变量 private KeyCode keyCodeExample; public MyCanvas (KeyCode keyCodeExample) { direction = "2=up 8=dn 4=lt 6=rt"; this.keyCodeExample = keyCodeExample; exit = new Command("Exit", Command.EXIT, 1);//定义退出命令对象 addCommand(exit); setCommandListener(this); } protected void paint(Graphics graphics)//定义绘画方法 { graphics.setColor(255,255,255);//设置颜色为红色 graphics.fillRect(0, 0, getWidth(), getHeight());//填充的起始点为(0,0) graphics.setColor(255, 0, 0); graphics.drawString(direction, 0, 0, Graphics.TOP | Graphics.LEFT); //开始绘画 } public void commandAction(Command command, Displayable displayable) { keyCodeExample.exitMIDlet(); //定义退出事件 } protected void keyPressed(int key)//定义按键 { switch ( key ){ case KEY_NUM2: direction = "up"; break; case KEY_NUM8: direction = "down"; break; case KEY_NUM4: direction = "left"; break; case KEY_NUM6: direction = "right"; break; case -1: direction = "上键"; break; case -2: direction = "下键"; break; case -3: direction = "左键"; break; case -4: direction = "右键"; break; case -5: direction = "确定"; break; case -10: direction = "拨号键"; break; case 42: direction = "*号键"; break; case 35: direction = "#键"; break; } repaint();//重绘组件 } } 两个文件放在一个文件夹下,文件夹名为 KeyCode.java 生成 启动 本文来源:https://www.wddqw.com/doc/a13dbb3f767f5acfa1c7cd98.html