GameCanvas及Sprite类的使用
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.lcdui.game.Sprite;
public class MyGameCanvas extends GameCanvas implements Runnable {
static final int UP=0;
static final int DOWN=1;
static final int LEFT=2;
static final int RIGHT=3;
int aup[]={12,12,13,13,14,14,15};
int adown[]={0,1,2,3};
int aleft[]={4,4,5,5,6,6,7,7};
int aright[]={8,9,10,11};
int mSpeed=5;
int mDir=0;
private boolean RUN=true;
private Graphics g;
private Sprite mHero;
private Image img;
public MyGameCanvas()
{
super(true);
g=this.getGraphics();
try {
img=Image.createImage("/hero.png");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
mHero=new Sprite(img,32,48);
System.out.println("执行到我了");
mHero.setPosition(20, 50);
new Thread(this).start();
}
public void moveto(int dir) {
// TODO Auto-generated method stub
switch(dir){
case UP:
if(dir!=mDir)
mHero.setFrameSequence(aup);
mHero.move(0, -mSpeed);
break;
case DOWN:
if(dir!=mDir)
mHero.setFrameSequence(adown);
mHero.move(0, mSpeed);
break;
case LEFT:
if(dir!=mDir)
mHero.setFrameSequence(aleft);
mHero.move(-mSpeed, 0);
break;
case RIGHT:
if(dir!=mDir)
mHero.setFrameSequence(aright);
mHero.move(mSpeed, 0);
break;
}
mDir=dir;
mHero.nextFrame();
}
public void handleKey(){
int key=getKeyStates();
if((key&UP_PRESSED)!=0) moveto(UP);
if((key&DOWN_PRESSED)!=0) moveto(DOWN);
if((key&LEFT_PRESSED)!=0) moveto(LEFT);
if((key&RIGHT_PRESSED)!=0) moveto(RIGHT);
}
public void run() {
while (RUN) {
try {
g.setColor(0);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
handleKey();
mHero.paint(g);
this.flushGraphics();/**/
Thread.sleep(100);
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
运行使用的效果是人物精灵的行走。
终于知道怎么去调试j2me项目了。。。。
在运行过程中,Console窗口中会出调试信息,可以根据信息去debug,
例如,当我运行到这一步的时候,
mHero=new Sprite(img,32,40);
意外中断了,抛出异常IllegalArgumentException,
查看文档,原来是尺寸不匹配,修改一下,编译通过~