在 Java Swing 應用程式開發中,經常需要根據檔案副檔名動態獲取對應的系統圖標,以提供更直觀的使用者介面。本文提供一個完整的可執行範例,示範如何利用 FileSystemView 獲取小圖標,並結合 ShellFolder 獲取大圖標。
Java 透過建立一個臨時檔案(指定副檔名),讓作業系統自動關聯對應的圖標資源。FileSystemView.getSystemIcon() 可取得小尺寸圖標(通常 16×16),而 ShellFolder.getIcon(true) 則能取得大尺寸圖標(通常 32×32 或 48×48)。
import java.io.File;
import java.io.IOException;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.BoxLayout;
import javax.swing.filechooser.FileSystemView;
import sun.awt.shell.ShellFolder;
public class FileIconExtractor extends JFrame implements ActionListener {
private JButton getIconBtn = new JButton("獲取圖標");
private JPanel iconPanel = new JPanel();
private JTextField extField = new JTextField();
private JLabel smallIconLabel = new JLabel("小圖標顯示區");
private JLabel bigIconLabel = new JLabel("大圖標顯示區");
public FileIconExtractor() {
this.setSize(400, 250);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
this.setTitle("檔案圖標提取工具");
getIconBtn.setActionCommand("GETICON");
getIconBtn.addActionListener(this);
iconPanel.setLayout(new BoxLayout(iconPanel, BoxLayout.Y_AXIS));
iconPanel.add(smallIconLabel);
iconPanel.add(bigIconLabel);
this.add(extField, BorderLayout.NORTH);
this.add(iconPanel, BorderLayout.CENTER);
this.add(getIconBtn, BorderLayout.SOUTH);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if ("GETICON".equals(e.getActionCommand())) {
String ext = extField.getText().trim();
if (ext.isEmpty()) return;
File tempFile = null;
try {
tempFile = File.createTempFile("icon", "." + ext);
FileSystemView view = FileSystemView.getFileSystemView();
Icon smallIcon = view.getSystemIcon(tempFile);
ShellFolder shellFolder = ShellFolder.getShellFolder(tempFile);
Icon bigIcon = new ImageIcon(shellFolder.getIcon(true));
setIconLabel(smallIcon, bigIcon);
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (tempFile != null && tempFile.exists()) {
tempFile.delete();
}
}
}
}
private void setIconLabel(Icon smallIcon, Icon bigIcon) {
smallIconLabel.setIcon(smallIcon);
smallIconLabel.setText("");
bigIconLabel.setIcon(bigIcon);
bigIconLabel.setText("");
}
public static void main(String[] args) {
new FileIconExtractor();
}
}
File.createTempFile() 建立帶指定副檔名的臨時檔,系統會自動根據檔案關聯分配圖標FileSystemView 屬標準 API,跨平台相容性佳;ShellFolder 屬 Sun 專有類別,僅限 Windows 平台finally 區塊刪除臨時檔,避免佔用磁碟空間此技術可應用於檔案管理器、上傳元件預覽、桌面搜尋工具等需要直觀顯示檔案類型的場景。若需支援更多平台,可考慮使用第三方圖標庫(如 FlatLaf 內建圖標)作為備選方案。