巧用繼承 Applet 並在 main 中實例化自身調用 init(),使同一類文件既可作為 Applet 嵌入網頁,又可作為獨立 Application 運行。核心技巧:Frame 充當頂級容器,add("Center", appletInstance) 掛載,init() 完成組件初始化。
public class Example extends Applet implements ActionListener {
public static void main(String[] args) {
Frame win = new Frame("Example");
Example applet = new Example();
win.add("Center", applet); // BorderLayout.CENTER
applet.init(); // 關鍵:手動觸發 Applet 生命周期
win.setSize(600, 360);
win.setVisible(true);
}
public void init() {
Button btn = new Button("OK");
btn.addActionListener(this);
add(btn);
}
public void actionPerformed(ActionEvent e) { ... }
}
| 特性 | Applet 模式 | Application 模式 |
|---|---|---|
| 入口 | 瀏覽器調用 init/start/stop/destroy | JVM 調用 main |
| 容器 | 瀏覽器插件區域 | 自建 Frame |
| 安全沙箱 | 受限(簽名可提權) | 無限制 |
| 參數傳遞 | HTML <param> | 命令行 args |
Applet 技術已淘汰(Java 9 標記移除,Java 11 徹底移除),雙模式僅具教學價值。現代替代:
Application + WebView 嵌入 Web。