使用Timer制作动画效果(转)

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.*;

public class TimerDemo extends MIDlet {

Display display;
StarField field = new StarField();
FieldMover mover = new FieldMover();
Timer timer = new Timer();

public TimerDemo() {
display = Display.getDisplay( this );
}

protected void destroyApp( boolean unconditional ) { }

protected void startApp() {
display.setCurrent( field );
timer.schedule( mover, 100, 100 );
}

protected void pauseApp() { }

public void exit(){
timer.cancel(); // stop scrolling
destroyApp( true );
notifyDestroyed();
}

class FieldMover extends TimerTask {
public void run(){
field.scroll();
}
}

class StarField extends Canvas {
int height;
int width;
int[] stars;
Random generator = new Random();
boolean painting = false;

public StarField(){
height = getHeight();
width = getWidth();
stars = new int[ height ];

for( int i = 0; i < height; ++i ){
stars[i] = -1;
}
}

public void scroll() {
if( painting ) return;

for( int i = height-1; i > 0; --i ){
stars[i] = stars[i-1];
}

stars[0] = ( generator.nextInt() % ( 3 * width ) ) / 2;
if( stars[0] >= width ){
stars[0] = -1;
}

repaint();
}

protected void paint( Graphics g ){
painting = true;

g.setColor( 0, 0, 0 );
g.fillRect( 0, 0, width, height );

g.setColor( 255, 255, 255 );

for( int y = 0; y < height; ++y ){
int x = stars[y];
if( x == -1 ) continue;

g.drawLine( x, y, x, y );
}

painting = false;
}

protected void keyPressed( int keyCode ){
exit();
}
}
}


来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/10294527/viewspace-127166/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/10294527/viewspace-127166/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值