Search code examples
javafxtreeviewjavafx-2cloudrail

Get selected tree node item full path in JavaFX


I have a TreeView component and content of it like this:

  • root
    • item1
    • item2
    • Folder1
      • Folder2
        • item101
    • item3

I want it to return the path /root/Folder1/Folder2/item101 when selected so that i can put that in the download command.

Below is the sample i have worked out till now(poorly made for testing purpose), problem is that it does not work inside folders, only in the root. I am using CloudRail API for Java.

List<CloudMetaData> data = cs.getChildren("/");
String path="";
String selectedName = treeView.getSelectionModel().getSelectedItem().getValue() ;
            System.out.println(selectedName); 
for (CloudMetaData cmd : data) {
                cache.put(cmd.getPath(), cmd);
                TreeItem<String> item = new TreeItem<>(cmd.getName());
                             if(selectedName.equals(cmd.getName())){
                                 path=cmd.getPath();
                             }
}
System.out.println(path);

Solution

  • You can do:

    StringBuilder pathBuilder = new StringBuilder();
    for (TreeItem<String> item = treeView.getSelectionModel().getSelectedItem();
        item != null ; item = item.getParent()) {
    
        pathBuilder.insert(0, item.getValue());
        pathBuilder.insert(0, "/");
    }
    String path = pathBuilder.toString();