简体   繁体   English

如何在JTree中存储到节点的路径?

[英]How to store path to a node in JTree?

I am working on a project where i want to create a series of Folders with structure and name similar to that of the JTree i have created. 我正在一个项目中,我想创建一系列文件夹,其结构和名称类似于我创建的JTree。

To Simplify : 简化:

If A is the root node and B and C are its Children, in the backend, Folder with name "A" is created at the location "C:\\Users\\Sami\\Desktop", Next both B and C are Created at "C:\\Users\\Sami\\Desktop\\A" 如果A是根节点,而B和C是其子节点,则在后端在名称“ C:\\ Users \\ Sami \\ Desktop”处创建名称为“ A”的文件夹,然后在“ C”处创建B和C :\\ Users \\ Sami \\ Desktop \\ A“

I am guessing that if i Traverse through each node and get their individual TreePath, it would make things easier. 我猜想如果我遍历每个节点并获得它们各自的TreePath,它将使事情变得容易。

Is there any other alternative that I can go for?. 我还有其他选择吗? If not how and where do i store the path to a particular node? 如果没有,我如何以及在哪里存储到特定节点的路径?

Please Help. 请帮忙。

The following code, is a SSCCE (short self contained correct example). 以下代码是SSCCE(简短的自包含正确示例)。 It transverses through all nodes in the tree and gets the path as a String. 它穿过树中的所有节点,并以String的形式获取路径。 From there you can parse the Strings to your purpose. 从那里,您可以解析字符串以达到您的目的。

import java.util.Enumeration;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

public class StoreTreePathExample {
    public static void main(String[] args){     
    JTree tree = new JTree();
    Enumeration en = ((DefaultMutableTreeNode)tree.getModel().getRoot()).preorderEnumeration();
      while(en.hasMoreElements()){
      TreePath path = new TreePath( ((DefaultMutableTreeNode)en.nextElement()).getPath() );
      String text = path.toString();
      System.out.println(text);
      }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM