本文提供一個基於 Swing JTree 的本地文件系統瀏覽器完整實現。核心邏輯採用遞歸遍歷目錄,構建 DefaultMutableTreeNode 樹模型,支持從控制台輸入根路徑動態加載,並展示圖標與滾動面板。代碼分為樹模型構建類 FilePathObj 與主界面類 PathTree 兩部分。
package com.swing.tree;
import java.io.File;
import javax.swing.tree.DefaultMutableTreeNode;
public class FilePathObj {
private DefaultMutableTreeNode root;
public DefaultMutableTreeNode getPathObj() {
return (root != null) ? root : new DefaultMutableTreeNode("null NODE");
}
public FilePathObj(String path) {
try { root = buildTree(path); }
catch (Exception e) { e.printStackTrace(); }
}
private DefaultMutableTreeNode buildTree(String dir) throws Exception {
File file = new File(dir);
if (!file.exists()) throw new Exception("file name is null");
if (file.isFile()) return new DefaultMutableTreeNode(file.getAbsolutePath());
File[] children = file.listFiles();
DefaultMutableTreeNode node = new DefaultMutableTreeNode(file.getAbsolutePath());
if (children == null || children.length == 0) return node;
for (File child : children) {
if (child.isDirectory())
node.add(buildTree(child.getAbsolutePath())); // 遞歸
else
node.add(new DefaultMutableTreeNode(child.getAbsolutePath()));
}
return node;
}
}
package com.tree;
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.io.*;
import com.swing.tree.FilePathObj;
public class PathTree extends JFrame {
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String path;
File f;
System.out.print("輸入要顯示的文件路徑: ");
while ((path = in.readLine()) != null) {
f = new File(path);
if (!f.exists() || f.isFile()) {
System.out.println("請輸入正確的目錄路徑");
continue;
}
new PathTree(path).setVisible(true);
break;
}
} catch (Exception e) { e.printStackTrace(); }
}
public PathTree(String path) {
super("Creating a Simple JTree");
FilePathObj obj = new FilePathObj(path);
JTree tree = new JTree(obj.getPathObj());
tree.setCursor(new Cursor(Cursor.HAND_CURSOR));
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(new JScrollPane(tree), BorderLayout.CENTER); // 可滾動
setSize(275, 500);
pack();
}
}
DefaultTreeCellRenderer)、添加右鍵菜單(打開、刪除、屬性)、集成文件過濾器、支持拖拽操作。此示例可作為文件管理器、代碼瀏覽器、資源選擇器等桌面應用的基礎模組。