首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

[JAVA100例] 第77例:Applet 使用 JAR 包加載資源

     編輯:Java 相關知識

本例演示如何將 Applet 所需的類文件與圖片等資源打包成 JAR,實現一次下載、本地運行,提升加載效率。

核心代碼

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ImageButtonApplet extends JApplet {
  private String path = "/img/ittoolbox.gif";
  private ImageIcon logoButtonIcon = new ImageIcon(getClass().getResource(path));

  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();
    }
  }
}

關鍵技術點

  • 資源加載:getClass().getResource(path) 從類路徑(含 JAR 內部)加載資源,路徑以 "/" 開頭表示類路徑根目錄
  • JAR 打包:將編譯後的 .class 文件與 img/ 目錄下的圖片一同打包:
    jar cvf ImageButtonApplet.jar ImageButtonApplet.class img/
  • HTML 引用 JAR:
    <applet code="ImageButtonApplet.class" archive="ImageButtonApplet.jar" width="200" height="100"></applet>
    archive 屬性指定 JAR 文件,瀏覽器會先下載 JAR 再從中加載類與資源
  • Swing 組件:繼承 JApplet,使用 JButton + ImageIcon 顯示圖片按鈕

優勢

  • 減少 HTTP 請求次數(類、圖片一次性下載)
  • 資源路徑統一管理,避免相對路徑錯誤
  • 支援簽名與安全沙箱機制

現代替代方案

Applet/JAR 技術已淘汰。現代 Web 開發請使用:

  • ES Modules + Webpack/Vite 打包:JS/CSS/圖片統一打包
  • Service Worker + Cache API:離線緩存資源
  • HTTP/2 多路復用:原生解決多請求性能問題
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved