Java JTree directory structure from file path
I've been trying to solve this problem, so maybe some of you can help me I have a list of files and their full paths (these are just strings of files on another machine), for example:
C:\a\b\c\file1.txt C:\a\b\c\file2.txt C:\a\d\file3.txt C:\e\file4.txt
I want to create a JTree to display such a directory structure:
C: a b c file1.txt file2.txt d file3.tct e file4.txt
I've been splitting strings on separators, so I finally get an array list, such as:
"C:","a","b","c","file1.txt" "C:","file2.txt" "C:","d","file3.txt" "C:","e","file4.txt"
Now I want to add one index at a time, but if the value already exists at that level, I skip to the next index That is, it will add the first array to the second array, and it will have "C:" at level 0 of the tree, so it will move to level 1 of the tree and index 1 of the array The problem I encountered was that I didn't know how to navigate the tree this way
Any recommendations and / or alternative implementation?
Solution
Let file complete the work of parsing and maintaining paths When you want to display files in JTree, you can also create a corresponding treemodel, such as filetreemodel, referencing here Because it implements the treemodel, it can be "set as the model of JTree, and then you have a simple old standard JTree". You can use any file as the root in any installed file system, for example:
TreeModel model = new FileTreeModel(new File(System.getProperty("user.dir"))); JTree tree = new JTree(model);