首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Java Swing 應用程式自訂標題列圖示完整教學:Toolkit 與 ImageIcon 兩大方案

     編輯:Java 程式設計入門

預設圖示痛點

Java Swing 視窗 (JFrame/JDialog) 預設顯示 Java 咖啡杯圖示。專業應用必須替換為品牌 Logo,提升辨識度。

方案一:Toolkit.getDefaultToolkit() - AWT 原生方案

適用於 Frame、Window 等 AWT 元件,也支援 Swing 視窗。

import java.awt.*;
import javax.swing.*;

public class CustomIconToolkit extends JFrame {
    public CustomIconToolkit() {
        setTitle("Toolkit 方案示範");
        setSize(400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 核心程式碼:3 行搞定
        Toolkit tk = Toolkit.getDefaultToolkit();
        Image icon = tk.createImage("logo.png"); // 支援相對/絕對路徑、URL、資源流
        setIconImage(icon);

        setVisible(true);
    }
    public static void main(String[] args) {
        new CustomIconToolkit();
    }
}

優點:無需額外匯入 Swing 套件、支援 AWT/Swing 通用。
缺點:createImage 為非同步載入,圖示可能延遲顯示;需自行處理路徑解析。

方案二:ImageIcon + setIconImage - Swing 標準方案 (推薦)

ImageIcon 會同步載入圖片,確保圖示即時顯示,且支援 ClassLoader 載入資源 (JAR 內圖片)。

import javax.swing.*;
import java.awt.*;

public class CustomIconSwing extends JFrame {
    public CustomIconSwing() {
        super("ImageIcon 方案示範");
        setSize(400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 方式 A:檔案系統路徑
        // ImageIcon icon = new ImageIcon("resources/logo.png");

        // 方式 B:ClassPath 資源 (打包成 JAR 後依然有效) —— 強烈推薦
        ImageIcon icon = new ImageIcon(getClass().getResource("/images/logo.png"));
        
        // 核心:設定視窗圖示
        setIconImage(icon.getImage());

        setVisible(true);
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(CustomIconSwing::new); // EDT 執行緒啟動
    }
}

進階:多解析度圖示 (HiDPI/Retina 螢幕完美適配)

現代作業系統支援多尺寸圖示 (16x16, 32x32, 48x48, 64x64...)。單一圖片縮放會模糊,應提供多尺寸集合。

import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.util.Arrays;

public class MultiResolutionIconDemo extends JFrame {
    public MultiResolutionIconDemo() {
        setTitle("多解析度圖示示範");
        setSize(400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        // 載入多尺寸圖片 (需預先準備 logo16.png, logo32.png, logo64.png...)
        List icons = Arrays.asList(
            new ImageIcon(getClass().getResource("/icons/logo16.png")).getImage(),
            new ImageIcon(getClass().getResource("/icons/logo32.png")).getImage(),
            new ImageIcon(getClass().getResource("/icons/logo48.png")).getImage(),
            new ImageIcon(getClass().getResource("/icons/logo64.png")).getImage()
        );
        
        // Java 9+ 可用 MultiResolutionImage (此處手動設定列表)
        setIconImages(icons); // 關鍵:setIconImages (複數) 接收 List

        setLocationRelativeTo(null);
        setVisible(true);
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(MultiResolutionIconDemo::new);
    }
}

額外技巧:自訂滑鼠游標

同樣使用 Toolkit 即可實現自訂游標:

Toolkit tk = Toolkit.getDefaultToolkit();
Image cursorImg = tk.getImage("cursor.png"); // 32x32 建議
Point hotspot = new Point(0, 0); // 熱點座標 (尖端位置)
Cursor customCursor = tk.createCustomCursor(cursorImg, hotspot, "CustomCursor");
setCursor(customCursor); // 元件級設定

路徑解析最佳實踐總結

常見問題排查

  • 圖示不顯示:檢查路徑大小寫 (Linux 區分大小寫)、確認圖片檔案已複製到輸出目錄 (Maven/Gradle resources 配置)、getResource 回傳 null 表示找不到資源。
  • JAR 內無圖示:必須用 Class.getResource(),檢查 jar tf app.jar 確認圖片已打包。
  • 透明背景變黑:使用 PNG 格式,確保 Alpha 通道正確;避免用 JPEG。

總結

  • 簡單需求:ImageIcon + setIconImage() 最穩健。
  • 高解析度螢幕:準備多尺寸圖片,使用 setIconImages(List<Image>)。
  • 資源載入:統一使用 ClassLoader 路徑 (getClass().getResource("/path")),相容 IDE 與 JAR 環境。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
場景推薦寫法說明
開發階段 (IDE 專案根目錄)new ImageIcon("resources/logo.png")相對專案根目錄
打包 JAR / 生產環境new ImageIcon(getClass().getResource("/images/logo.png"))從 ClassPath 載入,/ 代表 classpath 根目錄
外部設定檔指定路徑new ImageIcon(new File(configPath).toURI().toURL())File -> URI -> URL