程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> J2EE >> 采用多線程制作動畫

采用多線程制作動畫

編輯:J2EE

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<imgHeight)
{
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;
}


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved