採用多執行緒製作動畫(轉)

BSDLite發表於2007-08-15
採用多執行緒製作動畫(轉)[@more@]import java.awt.*;
import java.applet.*;

//注意到這個程式和Hello程式有什麼不一樣嗎?在這個程式中多了implements Runnable。
public class carton extends Applet implements Runnable
{
Image img;
Thread thd = null;
int i;
int imgWidth = 150;
int imgHeight = 150;
int ncyc=1 ;

String namestr[] = new String[5] ;

//當執行緒被啟用時開始執行run()函式。
public void run()
{
for (int j=0; j<5; j++)
{
namestr[j] = Integer.toString(j,8)+".jpg" ;
}

ncyc = -1 ;
while (true)
{
if (ncyc<=3) ncyc= ncyc+1 ; //初始化迴圈控制引數
else ncyc = 0 ;
img = getImage(getCodeBase(), namestr[ncyc]) ;

if (img != null)
{
i=imgHeight;
//repaint();
}

try {Thread.sleep(1000);} catch (InterruptedException e){}
i=0;
while (i {
repaint();
try {Thread.sleep(50);} catch (InterruptedException e){}
i+=4;
}
}
}

  //每次程式碼在新位置處重畫點陣圖,它都要呼叫repaint。該函式呼叫可過載的update方法。update方法與paint方法是相同的,這裡為啥不用怕paint(Graphics g)呢?除了paint方法在繪圖前要清除視窗,而update方法不清除(如果你把update方法改名為paint,你會看到有什麼不同)。
public void update(Graphics g)
{
if (img != null)
{
g.clipRect(0, 0, imgWidth, i);
g.drawImage(img, 0, i - imgHeight, null);
}
}

public void start()
{
if (thd == null)
{
thd = new Thread(this);
thd.start();
}
}

public void stop()
{
thd = null;
}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10617542/viewspace-958006/,如需轉載,請註明出處,否則將追究法律責任。

相關文章