Reputation: 19
The problem I got stuck into is getting TreeView nodes which contain specific Child to collapse/extend, not every TreeView node/parent to collapse. I tried recursion with a big failure and couldn't realise what the solution might be.
Here is a look at my code:
public void setTreeItem(Employee emp, TreeItem<Employee> root_tree) {
if (emp.equals(root_tree.getValue())) {
root_tree.setExpanded(false);
} else {
root_tree.setExpanded(true);
for (TreeItem<Employee> emps : root_tree.getChildren()) {
setTreeItem(emp, emps);
}
}
}
I get to this point and can't go any further. For reference, I checked out this topic but I couldn't really get the idea from that solution.
Those are pictures for demonstration:
this is a picture before checking for specific element
and this is picture after checking for that specific element (Mary Johnson).
As you can see it goes through the whole TreeView and extends all TreeView parents but after all Mary Johnson isn't there.
Upvotes: 2
Views: 1485
Reputation: 82461
You expand the TreeItem
s in non-terminal cases even if the item you search for is not a descendant of the item. Since you're traversing the whole tree, all nodes get expanded. To fix this provide feedback as return value:
public boolean setTreeItem(Employee emp, TreeItem<Employee> root_tree) {
if (emp.equals(root_tree.getValue())) {
root_tree.setExpanded(false);
return true;
} else {
for (TreeItem<Employee> emps : root_tree.getChildren()) {
if (setTreeItem(emp, emps)) {
// expand & return true, if item is a descendant of the current item
root_tree.setExpanded(true);
return true;
}
}
return false; // set expanded to false before returning here?
}
}
Instead of returning true
/false
you could also return the TreeItem
you containing the value you search for or null
and expand the items later in a loop
TreeItem<String> item = searchItem(someString, root);
if (item != null) {
item.setExpanded(false);
item = item.getParent();
while (item != null) {
item.setExpanded(true);
item = item.getParent();
}
}
Upvotes: 2