Java JTree directory structure from file paths
Asked Answered
A

3

3

I've been trying to get my head around this so maybe some of you can help me. I have a list of files with their full paths (these are just strings the files are on another machine), e.g:

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 show the directory structure like this:

C:
  a
   b
    c
     file1.txt
     file2.txt
   d
    file3.tct
  e
   file4.txt

I've been spliting the string on the seperator so I end up with a list of arrays like:

"C:","a","b","c","file1.txt"
"C:","a","b","c","file2.txt"
"C:","a","d","file3.txt"
"C:","e","file4.txt"

Now I want to add them an index at a time but if the value already exists at that level then to skip to the next index. i.e it would add the first array then on the second array it would go on level 0 of the tree there already exists a "C:" so move onto level 1 of the tree and index 1 of the array. The issues that I have is that Im not sure how to navigate the tree in such a way.

Any suggestions and or alternative implementations?

Apriorism answered 12/2, 2013 at 11:50 Comment(1)
See also File browser GUI.Originality
C
7

Let File do the work of parsing and maintaining paths. As you want to display the files in a JTree, you might as well create a corresponding TreeModel such as FileTreeModel, cited here. Because it implements TreeModel, it can "be set as a JTree's model and then you'd have a plain old standard JTree." You can use any File in any mounted file system as the root, for example:

TreeModel model = new FileTreeModel(new File(System.getProperty("user.dir")));
JTree tree = new JTree(model);

image

Capitol answered 12/2, 2013 at 16:31 Comment(0)
F
1

I'm not sure if FileTreeModel is the best way - it scans entire directories. From what you wrote, I guess you only want to display paths from your list.
You can achieve it by using TreePathsTreeModel described here: How I Show Windows Registry in jTree?
You just have to to convert filepaths from strings into TreePath objects.

Fridlund answered 5/4, 2013 at 6:47 Comment(0)
C
0

First, sort the Strings (before splitting them).

How to process the first line is obvious and I won't comment on it. In the second line, search the already built tree and check if the nodes already exist. After you find one that does not exist, follow the procedure done in the first line.

Conditioned answered 12/2, 2013 at 11:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.