Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

swing - Java JTree directory structure from file paths

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:acfile1.txt
C:acfile2.txt
C:adfile3.txt
C:efile4.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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...