JAR 文件基於 ZIP 格式壓縮,可減小體積、縮短下載時間,顯著提升 Applet 啟動速度。在 HTML/JSP 中指定:
<applet archive="name.jar" ...></applet>
編寫一個極小(<2KB)的 PreLoader Applet,負責顯示「請稍等...」提示並在後台加載真正的大型 Applet,避免用戶因長時間白屏而流失。關鍵實現:
AppletStub 接口,將存根傳遞給目標 AppletClass.forName() 動態加載目標類init()/start()實現 ImageObserver 接口的 imageUpdate() 方法,在圖像數據就緒時觸發 repaint(),實現單次重繪顯示完整圖像:
public boolean imageUpdate(Image img, int flags, int x, int y, int w, int h) {
if ((flags & ALLBITS) != 0) { repaint(); return false; }
if ((flags & (ERROR | ABORT)) != 0) { error = true; repaint(); return false; }
return true;
}
默認 update() 會清屏再調用 paint(),導致閃爍。覆蓋策略:
// 方案一:直接調用 paint()
public void update(Graphics g) { paint(g); }
// 方案二:僅重繪變化區域(更優)
public void update(Graphics g) {
g.clipRect(x, y, w, h);
paint(g);
}
針對縮放/滾動產生的高頻重繪事件,引入毫秒級延遲:僅處理最後一個事件,忽略「遲到」的事件。核心邏輯:
Image offscreen = createImage(width, height);
Graphics offG = offscreen.getGraphics();
offG.drawImage(img, 50, 50, this);
// 繪製完成後一次性翻轉顯示
myGraphics.drawImage(offscreen, 0, 0, this);
可配合低優先級線程繪圖,利用 CPU 空閒時間。
JDK 1.2 引入,擁有可訪問的數據緩衝區,包含 ColorModel 與光柵數據,構造簡單:
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
支持多種圖像類型(5/8位 RGB、灰度等),性能優於早期 Image 實現。
直接利用顯卡加速(如矩形填充),緩解 CPU/總線壓力。關鍵方法:
Component.createVolatileImage() 或 GraphicsConfiguration.createCompatibleVolatileImage() 創建validate(GraphicsConfiguration) 驗證表面有效性contentsLost() 檢查內容是否丟失(需重繪)性能提升程度取決於顯卡驅動支持。
滾動時直接在屏幕緩衝區移動像素,僅重繪新露出區域。Swing 中啟用:
scrollPane.setScrollMode(JScrollPane.BACKINGSTORE_SCROLL_MODE);
前台滾動始終受益,後台滾動可能降低性能。