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

SWT/JFace 文件瀏覽器實作教學:打造簡易 FileBrowser

     編輯:Java 相關知識

前言

在 Java 桌面開發中,SWT (Standard Widget Toolkit) 與 JFace 提供了強大的原生 GUI 元件。本文將透過一個完整的 FileBrowser 範例,示範如何使用 SWT 的 Table 元件建立一個簡易的檔案瀏覽器,支援目錄導航、檔案圖示顯示、大小與修改日期資訊。

核心架構與元件

範例採用單一類別封裝所有邏輯,主要包含:

  • Display 與 Shell:建立視窗環境與主視窗。
  • Table 與 TableColumn:以表格呈現檔案清單,欄位包括檔名、大小、修改日期。
  • ImageRegistry:快取檔案類型對應的系統圖示,避免重複載入。
  • 遞迴載入機制:setRootDirectory() 方法掃描指定目錄並填入表格。

關鍵程式碼解析

1. 初始化 UI 佈局

GridLayout gridLayout = new GridLayout();
shell.setLayout(gridLayout);
table = new Table(shell, SWT.BORDER | SWT.FULL_SELECTION);
table.setHeaderVisible(true);
// 建立三個欄位:檔名、大小、修改日期
TableColumn tcFileName = new TableColumn(table, SWT.LEFT);
tcFileName.setText("File name");
TableColumn tcFileSize = new TableColumn(table, SWT.RIGHT);
tcFileSize.setText("Size");
TableColumn tcDateModified = new TableColumn(table, SWT.RIGHT);
tcDateModified.setText("Date Modified");
// 設定欄寬
tcFileName.setWidth(200);
tcFileSize.setWidth(80);
tcDateModified.setWidth(180);
table.setLayoutData(new GridData(GridData.FILL_BOTH));

2. 目錄掃描與資料填充

private void setRootDirectory(File dir) {
    this.rootDir = dir;
    if (!(dir.exists() && dir.isDirectory()))
        throw new IllegalArgumentException("Invalid directory. ");
    table.removeAll();
    File[] files = dir.listFiles();
    for (int i = 0; files != null && i < files.length; i++) {
        File file = files[i];
        TableItem item = new TableItem(table, SWT.NULL);
        // 交替列背景色
        item.setBackground(i % 2 == 0 ? 
            shell.getDisplay().getSystemColor(SWT.COLOR_WHITE) : 
            shell.getDisplay().getSystemColor(SWT.COLOR_GRAY));
        item.setText(0, file.getName());
        item.setText(2, new Date(file.lastModified()).toString());
        if (file.isDirectory()) {
            item.setImage(0, iconFolder);
        } else {
            // 取得副檔名對應圖示
            int lastDot = file.getName().lastIndexOf('.');
            if (lastDot >= 0 && lastDot < file.getName().length()) {
                item.setImage(0, getIcon(file.getName().substring(lastDot + 1)));
            }
            long kbytes = file.length() / 1024;
            if (kbytes == 0) kbytes = 1;
            item.setText(1, kbytes + " KB");
        }
    }
}

3. 圖示快取機制

private ImageRegistry imageRegistry;
public Image getIcon(String extension) {
    if (imageRegistry == null) imageRegistry = new ImageRegistry();
    Image image = imageRegistry.get(extension);
    if (image != null) return image;
    Program program = Program.findProgram(extension);
    if (program != null) {
        image = new Image(shell.getDisplay(), program.getImageData());
        imageRegistry.put(extension, image);
    } else {
        image = iconFile;
    }
    return image;
}

進階擴充:Tree 版本與 JFace Viewer

原始碼中還包含兩個進階版本:

  1. Tree 版 FileBrowser (demo7):改用 Tree 元件呈現階層結構,支援工具列切換根目錄、雙擊啟動檔案、就地編輯重命名。
  2. JFace TreeViewer 版:採用 JFace 的 TreeViewer 搭配 ITreeContentProvider、LabelProvider、ViewerFilter、ViewerSorter 實現聲明式 UI,程式碼更模組化,支援「僅顯示目錄」、「刪除檔案」等功能。

執行與測試

直接執行 main 方法即可啟動視窗。預設掃描當前目錄(new File("."))或 C:/temp。請確保專案路徑下有 C:/icons/folder.gif 與 file.gif 圖示檔,或修改路徑指向專案資源。

總結

此範例展示了 SWT 低階 API 建立檔案瀏覽器的完整流程,涵蓋佈局管理、事件迴圈、檔案系統操作、圖示快取等實用技巧。進階版本則示範如何利用 JFace 的 MVC 架構簡化開發,是學習 SWT/JFace 絕佳的入門教材。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved