Java Applet 基础

Applet 的生命周期与历史地位,以及现代替代方案。

Beginner
Key PointsApplet 是嵌入浏览器的 Java 小程序,已被彻底淘汰(JDK 11 移除、浏览器不再支持),现代用 Web 前端或 JavaFX。

Applet 的生命周期

An applet has four lifecycle hooks: init runs once, start on each display, paint renders, and destroy before teardown. The browser drives them — there is no main.

MethodWhen
init()Once, after loading
start()Each time it becomes visible
paint(Graphics)When redraw is needed
stop()When it leaves the screen
destroy()Before unload

Hello World Applet

The classic form extends java.applet.Applet and overrides paint. It no longer compiles: the java.applet package was removed in JDK 11. Treat it as historical reference.

Java
// JDK 11 起无法编译:java.applet 已被移除
import java.applet.Applet;
import java.awt.Graphics;

public class HelloWorldApplet extends Applet {
    @Override
    public void paint(Graphics g) {
        g.drawString("Hello, World", 20, 20);
    }
}
If you still have applets, migrate the UI to HTML/CSS/JS and keep the logic as backend endpoints; for desktop needs use JavaFX or Swing.

现代替代方案

Browsers dropped the Java plugin long ago. For Java-based UIs use JavaFX (modern) or Swing (old but stable); for anything in a browser, use the web stack.

  • JavaFX — modern desktop UI, FXML + CSS styling
  • Swing — legacy desktop UI, still maintained
  • Web frontend + REST API — the default choice today
  • Compose Multiplatform / Flutter — cross-platform alternatives

Friends & Partners