如果想要做一個比較漂亮的Applet讓人家使用,一定會加上很多資源,比如圖片或者音效檔什麼的。
sun提供了一個有用的工具,jar。這個工具可以把這些資源檔合在一個檔案裡,避免頻繁的http request,
而且下載的jar檔案可以被緩衝,很爽吧。
但是如何正確引用jar中的資源呢?
比如我們打算顯示一個圖片按鈕,圖片相對路徑為./img/logo.gif,你可以自己隨便找一個gif圖片。
讓我們來看看我們想當然的做法。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ImageButtonApplet extends JApplet
{
private String path = "/img/logo.gif";
private ImageIcon logoButtonIcon = new ImageIcon(path);
/**Initialize the applet*/
public void init()
{
try
{
if (logoButtonIcon == null)
throw new Exception("cannot get the image!");
JButton iButton = new JButton(logoButtonIcon);
Container cp = this.getContentPane();
cp.add(iButton);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
這樣子編譯之後,把ImageButtonApplet.class和logo.gif保持相對路徑打進jar裡面,對應的HTML頁面代碼為<APPLET CODE = "ImageButtonApplet.class" CODEBASE = "." ARCHIVE = "test.jar" WIDTH = "200" HEIGHT = "200"></APPLET>,由於使用了Swing,
經過HTMLConverter預先處理之後,本以為能夠一舉成功,開啟頁面卻發現,拋出異常:
java.security.AccessControlException: access denied (java.io.FilePermission /img/logo.gif read)
這件事情也鬱悶了我很久,反覆實驗,不管path相對路徑還是什麼,都不能順利實現。
後來我研究了jdk內建的demo,發現demo在引用資源的時候,採用這樣的方法 getClass().getResource(String sourceName);
getClass()是Object的方法,返回一個對象的運行時類型,即CLass對象。