應用程式啟動時顯示圖片畫面,執行初始化工作(載入資源、連線資料庫、建構 UI)期間保持可見,初始化完成後自動關閉並進入主視窗。
private Window splashWindow;
private void prepareSplash() {
Toolkit tk = Toolkit.getDefaultToolkit();
splashWindow = new Window(this); // 無標題列、無邊框
Image img = tk.getImage("images" + File.separator + "splash.gif");
ImageCanvas canvas = new ImageCanvas(img); // 自訂 Canvas 繪圖
splashWindow.add(canvas, "Center");
// 置中螢幕
Dimension scr = tk.getScreenSize();
int w = img.getWidth(this), h = img.getHeight(this);
splashWindow.setLocation(scr.width/2 - w/2, scr.height/2 - h/2);
splashWindow.setSize(w, h);
}
ImageCanvas為繼承Canvas並覆寫paint(Graphics g)呼叫g.drawImage(img, 0, 0, this)的簡易類別。
private void startSplash() {
splashWindow.setVisible(true);
splashWindow.toFront();
}
public MyMainFrame() {
prepareSplash();
startSplash();
// 執行耗時初始化:資料庫連線、載入配置、建構複雜 UI 元件...
initDatabase();
initUIComponents();
loadResources();
// 全部完成後關閉 Splash
stopSplash();
// 顯示主視窗
setVisible(true);
}
private void stopSplash() {
splashWindow.dispose();
}
Window 而非 Frame,避免標題列與邊框干擾視覺效果。ImageCanvas 需實作 ImageObserver 或使用 MediaTracker 確保繪製時圖片就緒。repaint() 保持回應。SplashScreen 類別簡化實作(manifest 指定 SplashScreen-Image)。