本例演示如何將 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 cvf ImageButtonApplet.jar ImageButtonApplet.class img/<applet code="ImageButtonApplet.class" archive="ImageButtonApplet.jar" width="200" height="100"></applet>archive 屬性指定 JAR 文件,瀏覽器會先下載 JAR 再從中加載類與資源JApplet,使用 JButton + ImageIcon 顯示圖片按鈕Applet/JAR 技術已淘汰。現代 Web 開發請使用: