按键响应有3种情况,
1,当按键被按下时
protected void keyPressed(int keyCode)
2,当按键被松开时
protected void keyReleased(int keyCode)
3,当按键连续响应的时候
protected void keyRepeated(int keyCode)
在这里用最简单的一个事例来实现按键响应的功能:
首先我们载入资源图片:(不知道怎么在这个博客上贴图,读者可自己找一张飞机小图放如res文件里----最好移动的时候不需要更换资源图片的)
创建GameMidlet类,并启动Canvas类:
import javax.microedition.lcdui.Display;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class GameMidlet extends MIDlet {
private GameCan gc;
public GameMidlet() {
gc=new GameCan();
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() {
Display.getDisplay(this).setCurrent(gc);
}
}
/*--------------------------------------------------------------------------------------------------------------------*/
GameCan类的实现代码;
import java.io.IOException;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
public class GameCan extends Canvas implements Runnable {
private int width, height;
private Image plane;
private int planeY;
private int planeX;
private Thread trd;
private boolean isRung;
public GameCan() {
isRung=true;
width = getWidth();
height = getHeight();
//设置飞机的初始位子
planeX = width / 2;
planeY = height / 2;
try {
plane = Image.createImage("/player.png");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//构造并启动线程:
trd = new Thread(this);
trd.start();
}
protected void paint(Graphics g) {
//刷屏,不然会出现重影
g.setColor(0xffffff);
g.fillRect(0, 0, width, height);
//绘制飞机
g.drawImage(plane, planeX, planeY, 0);
}
protected void keyPressed(int keyCode) {
int action = getGameAction(keyCode);
switch (action) {//对操控对象上下左右的操作
case UP:
planeY-=10;
break;
case DOWN:
planeY+=10;
break;
case RIGHT:
planeX+=10;
break;
case LEFT:
planeX-=10;
break;
}
}
public void run() {
while(isRung){
try {
repaint();
trd.sleep(10L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
这样你的飞机就可以随着 你的操控动起来!
细心的读者可能会发现几个问题:
1:我们在这里只用了keyPressed的方法。
2:飞机是按一下才动一下,不能连续的响应。
困了```下次再继续吧````