在Applet中引用jar中的資源檔的方法

來源:互聯網
上載者:User

如果想要做一個比較漂亮的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對象。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.