本例綜合演示 Applet 參數獲取、雙緩衝繪圖技術、線程驅動動畫,實現帶陰影效果的文字橫向滾動廣告。
import java.awt.*;
import java.applet.*;
public class ShadowText extends Applet implements Runnable {
private Image img, offI;
private Graphics offG;
private Thread thread = null;
private int height, width;
private String text;
private int FontSize;
private Font font;
private int textcolor, backcolor, shadowcolor;
public void init() {
width = this.size().width;
height = this.size().height;
// 1. 獲取 HTML 參數(帶默認值)
String s = getParameter("Text");
text = (s != null) ? s : "Hello";
s = getParameter("FontSize");
FontSize = (s != null) ? Integer.parseInt(s) : 30;
s = getParameter("Fore");
textcolor = (s == null) ? 0x000000 : Integer.parseInt(s, 16);
s = getParameter("Back");
backcolor = (s == null) ? 0x000000 : Integer.parseInt(s, 16);
s = getParameter("shadow");
shadowcolor = (s == null) ? 0x000000 : Integer.parseInt(s, 16);
this.setBackground(new Color(backcolor));
// 2. 雙緩衝準備:預先繪製帶陰影的文字圖片
img = createImage(width + 300, height);
Graphics temp = img.getGraphics();
temp.setColor(new Color(backcolor));
temp.fillRect(0, 0, width, height);
temp.setColor(new Color(shadowcolor));
font = new Font("TimesRoman", Font.BOLD, FontSize);
temp.setFont(font);
temp.drawString(text, 10, height * 3 / 4); // 陰影
temp.setColor(new Color(textcolor));
temp.drawString(text, 10 - 3, height * 3 / 4 - 3); // 主文字(偏移產生陰影效果)
// 3. 離屏緩衝區
offI = createImage(width, height);
offG = offI.getGraphics();
}
public void start() {
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}
public void run() {
int x = width;
while (thread != null) {
try {
offG.drawImage(img, x, 0, this); // 在離屏緩衝區繪製滾動圖片
repaint();
thread.sleep(20);
} catch (InterruptedException e) {}
x -= 3;
if (x < -img.getWidth(this)) x = width; // 循環滾動
}
}
public void update(Graphics g) {
paint(g); // 避免默認 update 清屏導致閃爍
}
public void paint(Graphics g) {
g.drawImage(offI, 0, 0, this); // 將離屏緩衝區內容一次性繪製到屏幕
}
}
<applet code="ShadowText.class" width="400" height="100"> <param name="Text" value="歡迎來到 Java 世界!"> <param name="FontSize" value="36"> <param name="Fore" value="FF0000"> <!-- 紅色文字 --> <param name="Back" value="FFFFCC"> <!-- 淡黃背景 --> <param name="shadow" value="808080"> <!-- 灰色陰影 --> </applet>
getParameter(String name) 從 HTML <param> 獲取配置,支援十六進制顏色解析 Integer.parseInt(s, 16)offI(createImage 創建)paint() 一次性拷貝到屏幕update() 避免默認清屏導致閃爍img 預先繪製好帶陰影的長條文字圖片,滾動時只需 drawImage 位移,極大降低 CPU 佔用Runnable,run() 中控制位移與幀率(20ms/幀 ≈ 50fps)start() 啟動線程,stop()(未實現)應停止線程釋放資源| 技術 | Applet 方式 | 現代 Web 方式 |
|---|---|---|
| 參數傳遞 | <param> + getParameter() | HTML data-* 屬性 + JS 讀取 |
| 雙緩衝 | createImage + 手動管理 | Canvas 雙緩衝 / requestAnimationFrame |
| 動畫循環 | Thread + sleep() | requestAnimationFrame 遞歸調用 |
| 文字陰影 | 手動偏移繪製兩次 | CSS text-shadow / Canvas shadowColor |
| 滾動動畫 | 手動位移 drawImage | CSS animation / JS 修改 transform |
純文字滾動廣告現代首選 CSS @keyframes + text-shadow,零 JS、GPU 加速、響應式適配;複雜動畫用 Canvas + requestAnimationFrame 或 Web Animations API。