使用Timer制作动画效果

王朝other·作者佚名  2008-05-31
窄屏简体版  字體: |||超大  

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();

}

}

}

(出处:http://www.knowsky.com)

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航