GOXR3PLUS
GOXR3PLUS

Reputation: 7255

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 .

Upvotes: 3

Views: 5137

Answers (2)

lisyara
lisyara

Reputation: 121

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

Upvotes: 1

dark.semiQ
dark.semiQ

Reputation: 121

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;
}

Upvotes: 9

Related Questions