import javax.microedition.midlet.*;import javax.microedition.lcdui.*;import javax.io.IOException; public class SpriteTest extends MIDlet implements CommandListener,Runnable{ private static int SHIP_FRAME_WIDTH=16; private static int SHIP_FRAME_HEIGHT=16; private MyCanvas myCanvas; private Command quit; private Image[] shipFrames; private boolean running; private int currentFrame; class MyCanvas extends Canvas{ protected void paint(Graphics graphics){ graphics.setColor(0); graphics.fillRect(0,0,getWidth(),getHeight()); graphics.drawImage(shipFrames[currentFrame],getWidth()/2,getHeight ()/2,Graphics.HCENTER|Graphics.VCENTER); } } public SpriteTest(){ try{Image shipImage=Image.createImage("/005-Fighter05.png"); shipFrames.ImageSet.extractFrames (shipImage,4*SHIP_FRAME_WIDTH,0,4,4,SHIP_FRAME_WIDTH,SHIP_FRAME_HEIGHT); } catch(IOException ioe){System.out.println(unable to load image);} myCanvas=new MyCanvas(); quit=new Command("Quit",Command.EXIT.2); myCanvas.addCommand(quit); myCanbas.setCommandListener(this); running=true; Thread t=new Thread(this); t.start(); }//////////////////////////////////////////// public final static Image[] extractFrame(Image sourceImage,int sourceX,int sourceY,int framesWide,int framesHigh,int frameWidth,int frameHeight){ Image[] frames=new Image[framesWide*framesHigh]; int frameCount=0; for(int fy=0;fy<framesHigh;fy++) for(int fx=0;fx<framesWide;fx++) frame[frameCount++]=getImageRegion(sourceImage,sourceX+ (fx*frameWidth),sourceY+(fy*frameHeight),frameWidth,frameHeight); return frames; }//////////////////////////////////////////// public void run(){ while(running){ currentFrame++; if(currentFrame>15) currentFrame=0; myCanvas.repaint(); try{ Thread.sleep(1000); } catch(InterruptedException e){} }} protected void startApp() throws MIDletStateChangeException { Display.getDisplay(this).setCurrent(myCanvas); } protected void pauseApp(){} protected void destroyApp(boolean unconditional) throws MIDletStateChangeException{} public void commandAction(Command command,Displayable displayable) { try{ if(command==quit) {running=false; destroyApp(true); notifyDestroyed(); } } catch(MIDletStateChangeException me){System.out.println(me+"caught");} } }

评论