expand TreeView (parent)nodes which contains selec

2019-05-10 04:13发布

I have a TreeView existing out of User objects. The TreeView represents the hierarchy of the Users:

  • Master1
    • Super1
    • Super2
      • User1
      • User2
    • Super3
      • User3
    • Super4
  • Master2
  • ...

Every TreeItem is Collapsed when the TreeView is initialized. However, it can be that when the FXML is loaded, a TreeItem object is passed through from another FXML file. Eg: User3 has been passed through:

selectedUserTreeItem = (TreeItem<User>) currentNavigation.getPassthroughObject(); //this is the User3 TreeItem

I try to use a recursive function to expand all the parent nodes from the selecterUserTreeItem

if (selectedUserTreeItem != null) {
    expandTreeView(selectedUserTreeItem);
}

tvUsers.setRoot(rootItem);

This is what I have so far:

private void expandTreeView(TreeItem<User> selectedItem) {        
    if (selectedItem != null) {
        System.out.println(selectedItem);
        if (selectedItem.isLeaf() == false) {
            selectedItem.setExpanded(true);
        }
        TreeItem<User> parent = selectedItem.getParent();
        expandTreeView(parent);
    } else {
        System.out.println("null");
    }
}

I think it has to do something with the fact that the function is a void function and it should be returning a TreeItem object I suppose but for some reason I don't succeed in doing it.

Could someone point me in the right direction?

3条回答
Evening l夕情丶
2楼-- · 2019-05-10 04:35

No I don't think its because your method is returning void. Try setting your TreeView root first before expanding:

>>> tvUsers.setRoot(rootItem);

if (selectedUserTreeItem != null) {
    expandTreeView(selectedUserTreeItem);
}

If that doesn't work then try wrapping your initial expandTreeView() to run later:

Platform.runlater( new Runnable()
{
    public void run() { expandTreeView( selectedUserTreeItem ); }
};
查看更多
孤傲高冷的网名
3楼-- · 2019-05-10 04:44

Ok, I notice that in your expandTreeView() method you expand the node and then you recurse to the previous node to expand that. In my own code I expanded from the root to the leaf, so lets try that:

private void expandTreeView( TreeItem<User> selectedItem ) 
{
    if ( selectedItem != null ) 
    {
        expandTreeView( selectedItem.getParent() );

        if ( ! selectedItem.isLeaf() ) 
        {
            selectedItem.setExpanded( true );
        }
    }
}
查看更多
We Are One
4楼-- · 2019-05-10 04:58

Ok, I had the same problem and found that I had to delay the expansion a bit like this:

    Platform.runlater( new Task<Void>()
    {
        @Override
        protected Void call() throws Exception
        {
            Thread.sleep( 250 );
            return null;
        }

        @Override
        protected void succeeded()
        {
            expandTreeView( selectedUserTreeItem );
        }

    } );

You may have to try and vary the delay to get it to work in your case.

查看更多
登录 后发表回答