下边的代码说明了如何使用Timer类来实现简单的动画。
一个图像每隔固定的时间间隔不断地在屏幕上变换位置从而带来动画的效果
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Animation extends MIDlet implements CommandListener
{
public Display display;
public Animation() {}
public void startApp()
{
AnimationCanvas animation=new AnimationCanvas(this);
animation.startAnimation();
Display.getDisplay(this).setCurrent(animation);
}
public void pauseApp() {}
public void destroyApp( boolean unconditional ) {}
public void exit()
{
destroyApp(true);
notifyDestroyed();
}
public void commandAction(Command c, Displayable s){}
}
import javax.microedition.lcdui.*;
public class AnimationCanvas extends Canvas implements Runnable,
CommandListener
{
private Animation midlet;
int height;
int width;
int pad = 3;
boolean finishedAnimation = false;
int deltaY = 0;
private Command startCommand;
private Command exitCommand;
private Command aboutCommand;
public AnimationCanvas(Animation midlet)
{
this.midlet=midlet;
height = getHeight();
width = getWidth();
startCommand = new Command("Start",Command.BACK,1);
exitCommand = new Command("Exit",Command.SCREEN,0);
aboutCommand = new Command("About",Command.SCREEN,3);
}
public void paint(Graphics g)
{
g.setColor(0xFFFFFF);
g.fillRect(0,0,width,height);
g.setColor(0,255,0);
g.drawRoundRect(0,0,width-1,height-1,10,10);
if (finishedAnimation)
{
Form form = new Form("Animation");
form.append("Animation Complete/n");
form.addCommand(exitCommand);
form.setCommandListener(this);
Display.getDisplay(midlet).setCurrent(form);
}
else
{
Image img=null;
try
{
img = Image.createImage("/logo.png");
}
catch(Exception e){}
int ih = img.getHeight();
int iw = img.getWidth();
int imgX = (width-2)/2;
int imgY = (height-2)/2;
g.drawImage(img,imgX,imgY+deltaY,Graphics.VCENTER|Graphics.HCENTER);
removeCommand(exitCommand);
}
}
public void startAnimation()
{
try
{
finishedAnimation = false;
Thread t = new Thread(this);
t.start();
}
catch(Exception e){}
}
public void run()
{
try
{
int count = 0;
int sleep_time = 200;
while (true)
{
Thread.sleep(sleep_time);
count++;
if (count > 20)
{
finishedAnimation = true;
Thread.sleep(sleep_time);
repaint();
break;
}
if (count <=5 )
deltaY += 5;
else if (count >5 && count <=15)
deltaY -= 5;
else
deltaY +=5;
repaint();
}
}
catch(Exception e){}
}
public void commandAction(Command c,Displayable d)
{
if (c == exitCommand){
midlet.exit();}
}
}