Search code examples
javajavafxtreeviewjavafx-8

Javafx method for finding TreeItem by value returning null


I have created a method for searching a JavaFX TreeView and returning the TreeItem that matches a given value but it returns a TreeView with a value of null. I have added a couple of sysouts and it does correctly find the TreeItem but it still returns an empty one.

    public void addDirToTree(Directory parentDir, Directory newDir) {
        TreeItem<Label> parentTreeItem = findTreeItemByName(this.getRoot(),parentDir.getName());
        System.out.println(parentTreeItem);
        parentTreeItem.getChildren().add(createTreeItem(newDir));
    }
    
    
    private static TreeItem<Label> findTreeItemByName(TreeItem<Label> parentTreeItem, String name) {        
        for (TreeItem<Label> treeItem: parentTreeItem.getChildren()) {
            if (treeItem.getValue().getText().equals(name)) {
                System.out.println(treeItem);
                return treeItem;
            }
            findTreeItemByName(treeItem,name);
        }
        
        return parentTreeItem;
    }

Output:

TreeItem [ value: Label@402c2e44[styleClass=label]'new' ]
TreeItem [ value: null ]

These methods are inside a class that extends TreeView which is why this.getRoot() is passed


Solution

  • I don't understand why you have a TreeItem<Label>. The intention is that TreeItem should wrap a piece of data, not a UI element.

    Your recursion is incorrectly implemented. If the correct TreeItem is not found in the immediate descendants of the supplied TreeItem, you then recursively search the descendants of those items, but don't do anything with the any result you find, instead returning the originally-supplied item.

    You need something like this:

    private static TreeItem<String> findTreeItemByName(TreeItem<String> parentTreeItem, String name) {
        // if the supplied item is the one we're looking for, just return it:    
        if (parentTreeItem.getValue().equals(name)) {
            return parentTreeItem;
        }    
        // Recursively search child items and return one if found: 
        for (TreeItem<String> treeItem: parentTreeItem.getChildren()) {
            TreeItem<String> item = findTreeItemByName(treeItem,name);
            if (item != null) return item;
        }
        // We didn't find a match: return null:
        return null;
    }