如果想要做一個比較漂亮的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對象。
原來Class對象有getResource方法,在API文檔中就是這樣寫的:
public URL getResource(String name)
Finds a resource with a given name. This method returns null if no resource with this name is found. The rules for searching resources associated with a given class are implemented by the * defining class loader of the class.
This method delegates the call to its class loader, after making these changes to the resource name: if the resource name starts with "/", it is unchanged; otherwise, the package name is prepended to the resource name after converting "." to "/". If this object was loaded by the bootstrap loader, the call is delegated to ClassLoader.getSystemResource.
Parameters:
name - name of the desired resource
Returns:
a java.net.URL object.
Since:
JDK1.1
See Also:
ClassLoader
如法炮制,我把原來的
private ImageIcon LogoButtonIcon = new ImageIcon(path);
改成
private ImageIcon LogoButtonIcon = new ImageIcon(getClass().getResource(path));
編譯,jar,run,成功,無論是本機打開還是放到http服務器中,都沒有問題了。
這就是在Applet中引用jar中資源文件的KEY!