在 Java Applet 開發中,將類文件、圖片等資源打包成 JAR 檔案,能夠一次性下載到客戶端,提升載入效率。本例展示如何在 Applet 中透過 getClass().getResource() 從 JAR 包讀取圖片並顯示於按鈕上。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* Title: Applet 使用 JAR 包
* Description: 將類文件和圖片等資源文件打包,一次下載到本地。
* 本實例演示 Applet 使用這些資源
* Copyright: Copyright (c) 2003
* Filename: ImageButtonApplet.java
* @version 1.0
*/
public class ImageButtonApplet extends JApplet {
private String path = "/img/ittoolbox.gif";
private ImageIcon LogoButtonIcon = new ImageIcon(getClass().getResource(path));
/**
* 方法說明:初始化 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();
}
}
}
關鍵點:
/ 開頭,表示從 classpath 根目錄查找。ImageIcon 建構子直接接受 URL,自動處理圖片載入。getResource 返回 null,需自行檢查拋出異常。實務上,將圖片放入 src/img/ 目錄,編譯打包時會隨類文件一同進入 JAR,Applet 即可透過相同路徑存取。