Repository navigation
Expand file tree
/
Copy pathFileTreeExample.java
More file actions
48 lines (38 loc) · 1.64 KB
/
Copy pathFileTreeExample.java
File metadata and controls
48 lines (38 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.io.File;
public class FileTreeExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Root Directory and Subfolders");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
// Get the system root directories
File[] roots = File.listRoots();
// Create the root node for JTree
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root Directories");
for (File root : roots) {
DefaultMutableTreeNode rootDirNode = new DefaultMutableTreeNode(root.getPath());
rootNode.add(rootDirNode);
// Add subdirectories of the root directory
addSubFolders(root, rootDirNode);
}
// Create JTree with the root node
JTree tree = new JTree(rootNode);
JScrollPane scrollPane = new JScrollPane(tree);
frame.add(scrollPane);
frame.setVisible(true);
});
}
private static void addSubFolders(File folder, DefaultMutableTreeNode node) {
File[] subFolders = folder.listFiles(File::isDirectory);
if (subFolders != null) {
for (File subFolder : subFolders) {
DefaultMutableTreeNode subNode = new DefaultMutableTreeNode(subFolder.getName());
node.add(subNode);
// Recursively add subfolders of this folder
addSubFolders(subFolder, subNode);
}
}
}
}