您现在的位置: J2ME开发网 >> 参考源码 >> J2ME源码 >> 图形用户界面 >> 例子正文
使用Timer制作动画效果
作者:未知    例子来源:本站原创    点击数:    更新时间:2006-4-6
本例借助Timer和TimerTask实现了简单的动画效果,供入门参考

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.getDisplaythis );
  }

  protected void destroyAppboolean unconditional ) { }

  protected void startApp() {
    display.setCurrentfield );
    timer.schedulemover, 100100 );
  }

  protected void pauseApp() { }

  public void exit(){
    timer.cancel()// stop scrolling
    destroyApptrue );
    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 intheight ];

    forint i = 0; i < height; ++i ){
      stars[i= -1;
    }
  }

  public void scroll() {
    ifpainting return;

    forint i = height-1; i > 0; --i ){
      stars[i= stars[i-1];
    }

    stars[0generator.nextInt() * width ) ) 2;
    ifstars[0>= width ){
      stars[0= -1;
    }

    repaint();
  }

  protected void paintGraphics g ){
    painting = true;

    g.setColor00);
    g.fillRect00, width, height );

    g.setColor255255255 );

    forint y = 0; y < height; ++y ){
      int x = stars[y];
      ifx == -continue;

      g.drawLinex, y, x, y );
    }

    painting = false;
  }

  protected void keyPressedint keyCode ){
    exit();
  }
}
}