精华在于按钮事件机制
一个是长按一个是按下,另外值得一题的是除了0-9的数字键外都认为是游戏见
keyCode需要用getGameAction()转换一下在进行判断
import java.io.IOException;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class MIDlet1 extends MIDlet
{
private Display dis;
private Mycanvas mc =new Mycanvas();
protected void startApp() throws MIDletStateChangeException
{
dis=Display.getDisplay(this);
dis.setCurrent(mc);
}
class Mycanvas extends Canvas
{
private Image img;
int x,y,dir=Sprite.TRANS_NONE;;
protected Mycanvas()
{
x=0;y=0;
try
{
img=Image.createImage("/img.gif");
} catch (IOException e)
{
e.printStackTrace();
}
}
protected void paint(Graphics g)
{
g.setColor(255, 255, 255);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.drawRegion(img, 0, 0, img.getWidth(), img.getHeight(), dir, x, y, Graphics.LEFT|Graphics.TOP);
}
protected void keyRepeated(int keyCode)
{
int action;
action=this.getGameAction(keyCode);
switch(action)
{
case Canvas.UP: y-=5;break;
case Canvas.DOWN: y+=5;break;
case Canvas.LEFT: x-=5;break;
case Canvas.RIGHT: x+=5;break;
}
this.repaint();
}
protected void keyPressed(int keyCode)
{
int action;
action=this.getGameAction(keyCode);
if(action==Canvas.FIRE)
{
switch(dir)
{
case Sprite.TRANS_NONE: dir=Sprite.TRANS_MIRROR_ROT270; break;
case Sprite.TRANS_MIRROR_ROT90: dir=Sprite.TRANS_MIRROR_ROT180; break;
case Sprite.TRANS_MIRROR_ROT180: dir=Sprite.TRANS_MIRROR_ROT270; break;
case Sprite.TRANS_MIRROR_ROT270: dir=Sprite.TRANS_NONE; break;
}
this.repaint();
}
}
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException
{
}
protected void pauseApp()
{
}
}
posted on 2008-07-21 22:07
atskyline 阅读(639)
评论(0) 编辑 收藏 引用 所属分类:
J2ME笔记