国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

如何在Applet中引用jar中的資源文件

2019-11-18 14:47:47
字體:
供稿:網(wǎng)友

假如想要做一個(gè)比較漂亮的Applet讓人家使用,一定會加上很多資源,比如圖片或者聲音文件什么的。

sun提供了一個(gè)有用的工具,jar。這個(gè)工具可以把這些資源文件合在一個(gè)文件里,避免頻繁的http request,
而且下載的jar文件可以被緩存,很爽吧。

但是如何正確引用jar中的資源呢?

比如我們打算顯示一個(gè)圖片按鈕,圖片相對路徑為./img/logo.gif,你可以自己隨便找一個(gè)gif圖片。

讓我們來看看我們想當(dāng)然的做法。


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保持相對路徑打進(jìn)jar里面,對應(yīng)的Html頁面代碼為<APPLET CODE = "ImageButtonApplet.class" CODEBASE = "." ARCHIVE = "test.jar" WIDTH = "200" HEIGHT = "200"></APPLET>,由于使用了Swing,
經(jīng)過HTMLConverter預(yù)處理之后,本以為能夠一舉成功,打開頁面卻發(fā)現(xiàn),拋出異常:
java.security.accessControlException: access denied (java.io.FilePermission /img/logo.gif read)

這件事情也郁悶了我很久,反復(fù)試驗(yàn),不管path相對路徑還是什么,都不能順利實(shí)現(xiàn)。

后來我研究了jdk自帶的demo,發(fā)現(xiàn)demo在引用資源的時(shí)候,采用這樣的方法 getClass().getResource(String sourceName);

getClass()是Object的方法,返回一個(gè)對象的運(yùn)行時(shí)類型,即CLass對象。

原來Class對象有g(shù)etResource方法,在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,成功,無論是本機(jī)打開還是放到http服務(wù)器中,都沒有問題了。

這就是在Applet中引用jar中資源文件的KEY!

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 广安市| 元江| 通辽市| 武清区| 会昌县| 桐乡市| 和龙市| 饶河县| 禄丰县| 木兰县| 靖宇县| 林甸县| 华池县| 安宁市| 禹州市| 乐亭县| 贵州省| 桐城市| 新营市| 万载县| 莒南县| 镇原县| 华坪县| 清原| 张家港市| 阳泉市| 灵璧县| 龙井市| 平谷区| 阿拉善右旗| 德安县| 凤冈县| 寿光市| 温州市| 赫章县| 博客| 和硕县| 绥滨县| 体育| 定日县| 团风县|