示範如何透過 HTML `
import java.applet.Applet;
import java.awt.*;
import java.awt.image.ImageObserver;
public class ShadowText extends Applet implements Runnable {
private Image img; // 離屏緩衝:含陰影的完整文字圖
private Image offI; // 可視區緩衝
private Graphics offG;
private Thread thread;
private int width, height;
private String text = "Hello";
private int fontSize = 30;
private int textColor = 0x000000, backColor = 0xFFFFFF, shadowColor = 0x808080;
private Font font;
@Override
public void init() {
width = getSize().width;
height = getSize().height;
// 1. 解析 HTML 參數
String param = getParameter("Text");
if (param != null) text = param;
param = getParameter("FontSize");
if (param != null) fontSize = Integer.parseInt(param);
param = getParameter("Fore");
if (param != null) textColor = Integer.parseInt(param, 16);
param = getParameter("Back");
if (param != null) backColor = Integer.parseInt(param, 16);
param = getParameter("shadow");
if (param != null) shadowColor = Integer.parseInt(param, 16);
// 2. 預渲染帶陰影的文字圖 (寬度 +300px 供捲動)
img = createImage(width + 300, height);
Graphics g = img.getGraphics();
g.setColor(new Color(backColor));
g.fillRect(0, 0, width + 300, height);
font = new Font("TimesRoman", Font.BOLD, fontSize);
g.setFont(font);
// 陰影層 (右下偏移 3px)
g.setColor(new Color(shadowColor));
g.drawString(text, 10, height * 3 / 4);
// 正文字層
g.setColor(new Color(textColor));
g.drawString(text, 7, height * 3 / 4 - 3);
// 3. 初始化可視區緩衝
offI = createImage(width, height);
offG = offI.getGraphics();
}
@Override
public void start() {
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}
@Override
public void run() {
int x = width;
while (thread != null) {
try {
// 將預渲染圖按 x 位移繪製到可視緩衝
offG.drawImage(img, x, 0, this);
repaint();
Thread.sleep(20);
} catch (InterruptedException ignored) {}
x -= 3;
if (x < -img.getWidth(this)) x = width; // 循環捲動
}
}
@Override
public void update(Graphics g) { paint(g); } // 避免閃爍
@Override
public void paint(Graphics g) {
g.drawImage(offI, 0, 0, this);
}
}
<applet code="ShadowText.class" width="400" height="100"> <param name="Text" value="Welcome to Java Applet!"> <param name="FontSize" value="36"> <param name="Fore" value="FF0000"> <!-- 紅色文字 --> <param name="Back" value="FFFF00"> <!-- 黃色背景 --> <param name="shadow" value="808080"> <!-- 灰色陰影 --> </applet>
| 技術點 | 說明 |
|---|---|
| 參數傳遞 | `getParameter(String)` 返回 String,需自行轉型;缺省值在 init() 設定 |
| 雙緩衝動畫 | 離屏圖 `img` 預渲染靜態內容;`offI` 作為可視區緩衝,`paint()` 直接 `drawImage`,零閃爍 |
| 執行緒控制 | `start()` 啟動、`run()` 循環、`stop()` (未覆寫) 配合瀏覽器生命週期 |
| 顏色解析 | 十六進位字串 `Integer.parseInt(hex, 16)` → `Color` 建構子 |