Lifecycle of Applet
Lifecycle of Applet
Applet的生命周期中有四個狀態:初始態,運行態,停止態和消亡態. 與Applet的生命周期息息相關的是其以下方法:
void init() Called by the browser or applet viewer to inform this applet that it has been loaded into the system. |
Called by the browser or applet viewer to inform this applet that it should start its execution. |
void stop() Called by the browser or applet viewer to inform this applet that it should stop its execution. |
void destroy() Called by the browser or applet viewer to inform this applet that it is being reclaimed and that it should destroy any resources that it has allocated. |
當Applet首次被加載的時候, init()將被喚起. init()方法在Applet的生命周期內, 僅會被調用一次(就是在Applet被加載的時候). 因此, 這是進行資源初始化(比如界面布局, 數據庫連接的獲取等等)的最佳場所.
init()方法被調用之后, 接下來調用的便是start()方法. start()方法的調用將使得Applet的狀態成為active. 當Applet從最小化狀態恢復成最大化時[很多參考資料認為瀏覽器再度回到顯示Applet頁面時也會執行該方法, 但是經筆者試驗發現這種觀點似乎有失科學], 該方法均會被喚起. 因此, 與init()不同的是, 該方法可能會被調用多次.
stop()方法是start()方法的逆操作. 當Applet變成最小化時[與start()類似, 很多參考資料認為瀏覽器轉到其它頁面時,該方法也會被調用], 該方法將被喚起. 通常情況下, stop()方法中完成與start()方法中相反的操作. 例如: 在Applet處于active狀態的時候, 我們打算播放一個音樂片斷. 那么在Applet處于非活動狀態時, 我們可能希望停止該片斷的播送:
public void start(){
if(musicNotPlay()) //musicNotPlay用來判斷音樂片斷是否被播放過
musicClip.play();
else
musicClip.resume();
}
public void stop(){
if(!musicNotPlay())
musicClip.pause();
}
destroy()方法, 顧名思義, 是摧毀Applet時調用的方法. 因為Applet將要被摧毀了, 因此, 該Applet使用到的資源(比如數據庫鏈接等資源)應該被釋放.
范例
這是一個相當簡單的范例, 它只是在上述提及的方法中打印出一些信息:
AppletTest.java |
//<applet code="AppletTest" width="400" height="300"> //</applet> import javax.swing.*; public class AppletTest extends JApplet{ public void init(){ System.out.println("Initializing the applet...."); } public void start(){ System.out.println("Starting the applet...."); } public void stop(){ System.out.println("Stoping the applet..."); } public void destroy(){ System.out.println("Destroying the applet..."); } } |
程序運行效果(使用appletviewer):
程序啟動時(init() 和 start() 被調用)
將applet最小化(stop()被調用)
將applet恢復(start()再度被調用)
關閉appletviewer(stop()和destory()被調用)
在瀏覽器中執行
在appletviewer中執行的Applet運行得相當令人滿意. 下面我們將其移植在瀏覽器中執行. 測試環境為: Windows XP SP2 + JDK 5.0 + Internet Explorer 6.0.
首先撰寫HTML文件, 將Applet嵌入:
AppletTest.html |
<html> <head> <title>Applet的生命周期</title> </head> <body> 下面是一個用來測試的Applet(雖然它沒有顯示什么東西:))<br> <applet code="AppletTest" width="100" height="50"> </applet> <p>用來跳轉的鏈接<br> <UL> <li><a href="SomeOtherPage.html">Some other page</a></li> </UL> </p> </body> </html> |
同時再寫一個用來跳轉測試的HTML文件:
SomeOtherPage.html |
<html> <head> <title>用做跳轉的頁面</title> </head> <body> <a href="AppletTest.html">To AppletTest Page</a> </body> </html> |
這兩個文件都相當簡單, 不用再浪費口水J
執行效果:
執行AppletTest.html
控制臺中的輸出(init() & start())
點擊鏈接
控制臺中的輸出(stop() & destroy())
點擊鏈接,回到Applet頁面
重新加載(init() & start())
最小化瀏覽器窗口, 控制臺中無反應
從上面的圖中可以看到, 當瀏覽器跳轉到其它頁面時, Applet會被停止并且被摧毀. 當瀏覽器重新跳轉到Applet頁面的時候, Applet會被重新加載. 當瀏覽器窗口被最小化/恢復時, 不會有任何動作被執行到. 這和很多參考資料上的說法相悖.
ps: 測試環境WinXP SP2 + JDK5.0+IE6.0
posted on 2005-12-20 15:58 Guo Zhang 閱讀(385) 評論(0) 編輯 收藏 所屬分類: Java