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

首頁 > 學院 > 開發設計 > 正文

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

2019-11-18 11:58:11
字體:
來源:轉載
供稿:網友

  假如想要做一個比較漂亮的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頁面代碼為,由于使用了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!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 汪清县| 玉田县| 揭西县| 忻州市| 崇信县| 株洲市| 陇南市| 淮安市| 屏南县| 肇源县| 祁门县| 开原市| 海淀区| 墨竹工卡县| 昌都县| 东平县| 桃源县| 邢台市| 加查县| 玉环县| 宁晋县| 兴隆县| 商水县| 平远县| 浮山县| 蕲春县| 历史| 剑河县| 万源市| 财经| 博白县| 获嘉县| 乐山市| 永新县| 磐安县| 崇义县| 庆云县| 乐清市| 酒泉市| 东平县| 桃源县|