简体   繁体   中英

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.

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"

I am guessing that if i Traverse through each node and get their individual TreePath, it would make things easier.

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). It transverses through all nodes in the tree and gets the path as a 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);
      }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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