import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
//import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.lcdui.game.Sprite;
public class MyCanvas extends Canvas implements Runnable
{
boolean up=false,down=false,left=false,right=false;//将四个按键方向初始化赋为false
public Sprite m_MySprite;//定义一个Sprite类的引用
int n=0;
int z=0;
int[] aup ={6,7}; //这两帧是人物动画向上方向
int[] adown={0,1};
int[] aleft ={2,3};
int[] aright ={4,5};
Image image=null;//将初始图片赋空值
public MyCanvas()
{
super();
try
{
Image image=Image.createImage("/Hero.png");
m_MySprite=new Sprite(image,16,32);//新建一个精灵,第一个参数将精灵与图片对应,后两个参数分别是其宽和高
m_MySprite.setFrame(0);//设置精灵当前显示的帧编号
int nPosx=getWidth()/2-25;//取得屏幕宽度
int nPosy=getHeight()/2-25;//取得屏幕高度
m_MySprite.setPosition(nPosx, nPosy );//设置精灵位置
//m_MySprite.defineReferencePixel(8, 8);
// m_MySprite.setRefPixelPosition(nPosx, nPosy);
}
catch(Exception e){}
start();
image=null;
}
protected void paint(Graphics g)
{
g.setColor(0);
g.fillRect(0, 0, getWidth(), getHeight());//清屏
m_MySprite.paint(g);//显示精灵当前显示的帧图象
int n=m_MySprite.getFrame();//得到精灵当前显示的帧编号
n++;
if(n>=8)
{
n=0;
}
m_MySprite.setFrame(n);//更换精灵显示的帧遍号让其不大于上限
}
public void cycle()
{
if(m_MySprite.getX()>0&&m_MySprite.getX()<getWidth()-16&&m_MySprite.getY()>0&&m_MySprite.getY()<getHeight()-32)
{
if(up)
{
m_MySprite.setPosition(m_MySprite.getX(), m_MySprite.getY()-2);//上方向移动,每次移动走两个象数单位
m_MySprite.setFrameSequence(aup);//设置人物帧序列号
}
if(down)
{
m_MySprite.setPosition(m_MySprite.getX(), m_MySprite.getY()+2);//下
m_MySprite.setFrameSequence(adown);
}
if(left)
{
m_MySprite.setPosition(m_MySprite.getX()-2, m_MySprite.getY()); //左
m_MySprite.setFrameSequence(aleft);
}
if(right)//对应键盘方向键
{
m_MySprite.setPosition(m_MySprite.getX()+2, m_MySprite.getY()); //右
m_MySprite.setFrameSequence(aright);
}
}
}
public void keyPressed(int keycode)
{
switch(getGameAction(keycode))
{
case UP:
up=true;
break;
case DOWN:
down=true;
break;
case LEFT:
left=true;
break;
case RIGHT:
right=true;
break;
}
}
public void keyReleased(int keycode)
{
switch(getGameAction(keycode))
{
case UP:
up=false;
break;
case DOWN:
down=false;
break;
case LEFT:
left=false;
break;
case RIGHT:
right=false;
break;
}
}
public void run()//重写run方法
{
while(true)
{
try
{
System.out.println(1111);
repaint();
Thread.sleep(200);
cycle();
}
catch(Exception e)
{
System.out.println("线程当中有错误"+e);
}
}
}
public void start()
{
Thread t= new Thread (this);
t.start();
}
}
这是我代码.
------解决方案--------------------------------------------------------