<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
線程是程序的一部分,是系統調度的基本單位。線程是控制動畫的理想選擇。將動畫的工作放在線程上,可以釋放出程序的其他部分來處理別的任務。
線程的現實是通過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 );
}
}