Search code examples
javajavafxtreeview

JavaFX TreeView find TreeItem in any depth matching a given value


I am trying to create a method that does what title says . Let's say i have the below TreeView , i want to add a search functionality , in which the user can give for example a valuedesktop and using that method to get the first TreeItem which has the given value treeItem.getValue();

I need exactly this treeView.getChildren_InAnyDepth_MatchingValue("value");.

Let's say i want it to start searching from the root of the TreeView.

enter image description here


Java Code :

/**
* Find the first TreeItem matching the given value
* 
* @param item
*/
public TreeItem getTreeViewItem(TreeItem<String> item , String value) {
    if (item != null && item.getValue().equals(value))
        return  item;
                
    for (TreeItem<String> child : item.getChildren())
        getTreeViewItem(child, value);
                
    return null;
}

The above code always returns null for some reason , i can't figure out 6 hours now .


Solution

  • I know this is old but i am going to answer this To help others.

    public static TreeItem getTreeViewItem(TreeItem<String> item , String value) 
    {
      if (item != null && item.getValue().equals(value))
        return  item;
    
      for (TreeItem<String> child : item.getChildren()){
       TreeItem<String> s=getTreeViewItem(child, value);
       if(s!=null)
           return s;
    
      }
      return null;
    }