?? secnodanimation.java
字號:
// 程序:使用線程播放動畫
// 范例文件:SecnodAnimation.java
import java.awt.*;
import java.net.*;
import java.applet.*;
public class SecnodAnimation extends Applet implements Runnable
{
URL ErrorHTML; //錯誤頁面的URL
int currentImage; //目前圖像
Image Animation[]; //動畫圖像
MediaTracker MT; //圖像追蹤器
Thread newThread; //新線程
//===============init()函數和第一版本相同===========================
public void init()
{
currentImage = 0; //指定目前圖像為第一張圖像
Animation = new Image[8]; //與使用八張動畫圖像
MT = new MediaTracker(this);
for(int i=0;i<8;i++) //注意此循環中的程序代碼
{
Animation[i]
= getImage(getDocumentBase(),"Images/Freedom" + (i+1) + ".gif");
MT.addImage(Animation[i],0);
}
try
{
showStatus("圖像加載中..."); //在狀態列顯示信息
MT.waitForAll(); //等待所有圖像下載
}
catch(InterruptedException E) //若捕捉到例外
{
try //建立錯誤頁面的URL
{
ErrorHTML = new URL(getCodeBase().toString() + "ErrorHTML.html");
}
catch(MalformedURLException ME){ }
getAppletContext().showDocument(ErrorHTML); //轉移頁面
}
}
//==================================================================
public void start() //start()函數
{
//建立與啟動新線程
newThread = new Thread(this);
newThread.start();
}
public void stop() //stop()函數
{
newThread = null; //將線程設為null
}
//=================================================================
public void paint(Graphics g) //已將差勁的動畫循環抽離
{
//繪制目前圖像
g.drawImage(Animation[currentImage],50,10,250,250,this);
}
//===============新的動畫循環在此===================================
public void run()
{
while(newThread != null)
{
repaint(); //重新繪制圖像
try
{
Thread.sleep(125); //暫停程序執行125毫秒
}
catch(InterruptedException E)
{
try //建立錯誤頁面的URL
{
ErrorHTML = new URL(getCodeBase().toString() + "ErrorHTML.html");
}
catch(MalformedURLException ME){ }
getAppletContext().showDocument(ErrorHTML); //轉移頁面
}
if(currentImage == 7) //如果已經播放到最后一張圖像
currentImage = 0; //指定目前圖像為第一張圖像
else
currentImage = currentImage + 1; //指定圖像為下一張圖像
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -