Java 除了支援圖形與圖像繪製,也允許連續播放多張圖片,也就是動畫。原理不複雜:用 Graphics 類別的 drawImage() 在螢幕上畫出目前這一格,接著讓執行緒睡一會兒,再換成下一張圖,如此反覆循環,連續畫出的「格」在人眼裡就變成了運動。
要每秒更新畫面好幾次,就必須有一條專門的執行緒來驅動這個迴圈:它負責記住目前是第幾格,並週期性地要求重繪。實作上有兩條路——寫一個繼承 Thread 的類別,或讓 Applet 實作 Runnable 介面。後者更常用,因為 Applet 本來就有單一繼承的束縛。
寫動畫時幾乎一定會遇到畫面閃爍。原因有兩個:
paint() 之前,Java 會先用背景色把整个區域重畫一次。於是當 JVM 正在算下一格時,使用者看到的就是一片空白背景。當 AWT 收到重繪請求時,實際上呼叫的是 update();它預設會先清掉 Applet 背景,然後才呼叫 paint()。把繪圖邏輯搬到覆寫後的 update() 裡,就能避免每次重繪都把整個區域清空:
public void update(Graphics g)
{
// 原版行為:先用背景色填满,再画前景
g.setColor(getBackground());
g.fillRect(0, 0, width, height);
g.setColor(getForeground());
paint(g);
}
也就是說,要消除閃爍,就必須改寫 update(),讓它不去清整個畫面,只清該清的部分。最極簡的版本甚至只是:
public void update(Graphics g){ paint(g); }
另一個有效手段是雙緩衝,在多數動畫 Applet 裡都能看到。做法是先在記憶體中建立一張離屏圖像,把這一格拉到圖像上,最後用一次 drawImage() 把整張圖一次貼到螢幕。好處是大部分繪製都在離屏進行,而「一次貼上」比「直接在螢幕上逐點畫」有效率得多。
代價是必須配置一張與畫布同尺寸的後台圖像。畫面大時,這塊記憶體並不便宜;而且使用雙緩衝時,記得同時覆寫 update(),否則清除背景的動作還是會把成果抹掉。
下面這個 Applet 每秒更新一次,用 SimpleDateFormat 取時間,再以三角函數算出時針、分針、秒針的座標,並只擦除上一格畫過的線段:
import java.util.*;
import java.awt.*;
import java.applet.*;
import java.text.*;
public class AnimatorDemo extends Applet implements Runnable
{
Thread timer; // 顯示時鐘的執行緒
int lastxs, lastys, lastxm,
lastym, lastxh, lastyh; // 上一格的指針座標
SimpleDateFormat formatter;
String lastdate; // 上一格顯示的文字
Font clockFaceFont;
Date currentDate;
Color handColor, numberColor;
public void init() {
lastxs = lastys = lastxm = lastym = lastxh = lastyh = 0;
formatter = new SimpleDateFormat("yyyy EEE MMM dd hh:mm:ss ");
currentDate = new Date();
lastdate = formatter.format(currentDate);
clockFaceFont = new Font("Serif", Font.PLAIN, 14);
handColor = Color.blue;
numberColor = Color.darkGray;
resize(300, 300);
}
// 畫圓用的 Bresenham 演算法(此處省略 plotpoints 的細節)
public void circle(int x0, int y0, int r, Graphics g) {
int x = 0, y = r;
float d = 1.25f - r;
plotpoints(x0, y0, x, y, g);
while (y > x) {
if (d < 0) { d = d + 2 * x + 3; x++; }
else { d = d + 2 * (x - y) + 5; x++; y--; }
plotpoints(x0, y0, x, y, g);
}
}
public void paint(Graphics g) {
int xcenter = 80, ycenter = 55;
Date now = new Date();
// 以「秒/分/時」換算成角度,再轉為座標
int s = now.getSeconds();
int m = now.getMinutes();
int h = now.getHours();
int xs = (int)(Math.cos(s * 3.14f/30 - 3.14f/2) * 45 + xcenter);
int ys = (int)(Math.sin(s * 3.14f/30 - 3.14f/2) * 45 + ycenter);
int xm = (int)(Math.cos(m * 3.14f/30 - 3.14f/2) * 40 + xcenter);
int ym = (int)(Math.sin(m * 3.14f/30 - 3.14f/2) * 40 + ycenter);
int xh = (int)(Math.cos((h*30 + m/2) * 3.14f/180 - 3.14f/2) * 30 + xcenter);
int yh = (int)(Math.sin((h*30 + m/2) * 3.14f/180 - 3.14f/2) * 30 + ycenter);
// 表盤與刻度
g.setFont(clockFaceFont);
g.setColor(handColor);
circle(xcenter, ycenter, 50, g);
g.setColor(numberColor);
g.drawString("9", xcenter-45, ycenter+3);
g.drawString("3", xcenter+40, ycenter+3);
g.drawString("12", xcenter-5, ycenter-37);
g.drawString("6", xcenter-3, ycenter+45);
// 关键:用背景色擦掉「上一格」畫過的線,而不是清整塊畫面
g.setColor(getBackground());
if (xs != lastxs || ys != lastys)
g.drawLine(xcenter, ycenter, lastxs, lastys);
if (xm != lastxm || ym != lastym) {
g.drawLine(xcenter, ycenter-1, lastxm, lastym);
g.drawLine(xcenter-1, ycenter, lastxm, lastym);
}
if (xh != lastxh || yh != lastyh) {
g.drawLine(xcenter, ycenter-1, lastxh, lastyh);
g.drawLine(xcenter-1, ycenter, lastxh, lastyh);
}
// 畫上新的一格
g.setColor(numberColor);
g.drawString(new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy").format(now), 5, 125);
g.drawLine(xcenter, ycenter, xs, ys);
g.setColor(handColor);
g.drawLine(xcenter, ycenter-1, xm, ym);
g.drawLine(xcenter-1, ycenter, xm, ym);
g.drawLine(xcenter, ycenter-1, xh, yh);
g.drawLine(xcenter-1, ycenter, xh, yh);
lastxs = xs; lastys = ys;
lastxm = xm; lastym = ym;
lastxh = xh; lastyh = yh;
}
public void start() { timer = new Thread(this); timer.start(); }
public void stop() { timer = null; }
public void run() {
Thread me = Thread.currentThread();
while (timer == me) {
try { Thread.currentThread().sleep(1000); }
catch (InterruptedException e) { }
repaint();
}
}
// 覆寫 update(),直接呼叫 paint(),不再清整塊背景
public void update(Graphics g) { paint(g); }
}
<html>
<head><title>一個時鐘的例子</title></head>
<body>
<hr>
<applet codebase="." align="middle"
code="AnimatorDemo.class" width="200" height="150">
</applet>
</body>
</html>
這個範例的價值不在時鐘本身,而在兩個觀念:動畫的本質是「只重畫改變的部分」,以及把绘制搬到離屏再一次貼上。這兩招在今天的 Canvas、WebGL 甚至任何即時渲染系統裡都還在用,只是 API 換了名字。
另外要提醒:Java Applet 早已被主流瀏覽器全面淘汰(NPAPI 外掛機制自 2017 年起陸續移除),這份程式碼現在只能當作 Java 2D 繪圖與執行緒觀念的教材閱讀。想重現同樣的效果,用 Canvas 搭配 requestAnimationFrame 會合適得多。