线程是程序的一部分,是系统调度的基本单位。线程是控制动画的理想选择。将动画的工作放在线程上,可以释放出程序的其他部分来处理别的任务。
线程的现实是通过java.lang中的Thread类,要使某一个类能使用线程,必须实现Runnable接口,该接口包含了唯一一个方法run()。run()方法是线程类的核心,--------动画程序中产生运动。通过调用线程的start ()方法,致使run()方法被调用。下边这个程序描绘了一个运动中的圆。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Cartoon extends JApplet implements Runnable
{
Graphics screenBuffer = null;//创建图形缓冲区
Image screenImage = null;
private Thread runner;
private int x = 5;
private int move = 1;
public void init ( )
{
screenImage = createImage ( 230, 160 );
screenBuffer = screenImage.getGraphics ( );
}
public void start ( )
{
if (runner == null)
{
runner = new Thread( this );
runner.start();
}
}
public void run( )
{
Thread circle = Thread.currentThread ( );
while ( runner == circle )//指向同一对象,便开始运行
{
x += move;
if ( ( x > 105 ) ( x < 5 ))
move *= -1;
repaint ( );
}
}
public void drawCircle( Graphics gc )
{
Graphics2D g2D = ( Graphics2D ) gc;
g2D.setColor ( Color.blue );
g2D.fillRect ( 0, 0, 100, 100 );
g2D.setColor ( Color.yellow );
g2D.fillRect ( 100, 0, 100, 100 );
g2D.setColor ( Color.red );
g2D.fillOval ( x, 5, 90, 90 );
}
public void paint( Graphics g )
{
screenBuffer.setColor ( Color.white );
screenBuffer.fillRect (0,0,96,60);
drawCircle ( screenBuffer );
//将缓冲区的图像复制到主缓冲区中
g.drawImage ( screenImage, 130, 100, this );
}
}