Java JTree目录结构从文件路径 [英] Java JTree directory structure from file paths

查看:309
本文介绍了Java JTree目录结构从文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图让我的头脑,所以也许有些人可以帮助我。我有一个包含完整路径的文件列表(这些文件只是文件在另一台机器上的字符串),例如:

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

我想创建一个Jtree显示目录结构如下:

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

我已经将字符串分隔在分隔符上,所以我最终得到一个数组列表,如:

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

现在我想一次添加一个索引,但是如果该值已经存在于该级别,那么跳到下一个指数。那么它会添加第一个数组,然后在第二个数组上,它将在树的0级存在,它已经存在一个C:,所以移动到树的第1级和数组的索引1。我的问题是,我不知道如何以这种方式导航树。



任何建议或替代实现?

解决方案

文件做解析和维护路径的工作。当您想在 JTree 中显示文件时,您可以创建一个相应的 TreeModel ,例如 FileTreeModel ,引用此处。因为它实现了 TreeModel ,它可以被设置为一个 JTree 的模型,然后你会有一个平原旧标准 JTree 。您可以在任何挂载的文件系统中使用任何文件作为根目录,例如:

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


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?

解决方案

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);

这篇关于Java JTree目录结构从文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆