import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.io.File;
public class FolderTree extends JFrame {
public FolderTree(String path) {
super("Folder Tree");
setDefaultCloseOperation(EXIT_ON_CLOSE);
File fileRoot = new File(path);
DefaultMutableTreeNode root = new DefaultMutableTreeNode(fileRoot.getName());
addNodes(root, fileRoot);
JTree tree = new JTree(root);
add(new JScrollPane(tree));
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void addNodes(DefaultMutableTreeNode parent, File fileParent) {
File[] files = fileParent.listFiles();
if (files != null) {
for (File file : files) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(file.getName());
parent.add(node);
if (file.isDirectory()) {
addNodes(node, file);
}
}
}
}
public static void main(String[] args) {
new FolderTree("/Users/username/Documents/folder");
}
}
06-28
1229
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)