Java Applet 廣泛應用於網頁圖像展示,支援 GIF、JPEG 等常見格式。本文系統介紹從基本 getImage/drawImage 使用,到雙緩衝技術消除閃爍的完整實作方案。
Image picture;picture = getImage(getCodeBase(), "ImageFileName.GIF");getCodeBase() 回傳 Applet 所在 URL,第二參數為相對路徑檔名。paint(Graphics g) 中呼叫 g.drawImage(picture, x, y, this);,最後一個參數 this 實作 ImageObserver 介面以追蹤載入進度。import java.awt.*;
import java.applet.*;
public class ShowImage extends Applet {
Image picture;
public void init() {
picture = getImage(getCodeBase(), "Image.gif");
}
public void paint(Graphics g) {
g.drawImage(picture, 0, 0, this);
}
}
對應 HTML 標籤:
<APPLET CODE="ShowImage.class" WIDTH=600 HEIGHT=400></APPLET>
drawImage 會啟動獨立執行緒邊載入邊繪製,導致畫面逐行出現、閃爍嚴重。解決方案是雙緩衝技術:先將完整圖像繪製至記憶體離屏影像,再一次性繪至螢幕。
import java.awt.*;
import java.applet.*;
public class BackgroundImage extends Applet {
Image picture;
boolean imageLoaded = false;
Image offScreenImage;
Graphics offScreenGC;
public void init() {
picture = getImage(getCodeBase(), "Image.gif");
// 建立離屏影像與繪圖環境
offScreenImage = createImage(size().width, size().height);
offScreenGC = offScreenImage.getGraphics();
offScreenGC.drawImage(picture, 0, 0, this); // 離屏繪製
}
public void paint(Graphics g) {
if (imageLoaded) {
g.drawImage(picture, 0, 0, null); // 已載入完成,第四參數用 null
showStatus("Done");
} else {
showStatus("Loading image");
}
}
// 追蹤圖像載入進度
public boolean imageUpdate(Image img, int infoflags, int x, int y, int w, int h) {
if ((infoflags & ALLBITS) != 0) {
imageLoaded = true;
repaint(); // 觸發 paint 重繪
return false; // 停止後續呼叫
}
return true; // 繼續追蹤
}
}
createImage(width, height) 建立離屏影像緩衝區。imageUpdate 回調監控載入狀態,ALLBITS 旗標表示載入完成。paint 使用 null 替代 this,避免重複觸發 imageUpdate。雙緩衝雖需額外記憶體,但能實現平滑無閃爍的圖像顯示,是專業 Applet 開發的必備技巧。