19

Is there a way to set two root nodes for one TreeView?

I found many example if simple TreeView but there is no useful example for my case.

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808

1 Answers1

51

No: a tree only has one root node.

To get the effect you want, create a dummy root node and add your two nodes to it. Create the TreeView with the dummy root node and call tree.setShowRoot(false), so the dummy node does not appear.

final TreeItem<String> root1 = new TreeItem<>("root 1");
final TreeItem<String> root2 = new TreeItem<>("root 2");
final TreeView<String> tree = createTreeView(root1, root2);

// ...

private TreeView<String> createTreeView(TreeItem<String> root1, TreeItem<String> root2) {
    TreeItem<String> dummyRoot = new TreeItem<>();
    dummyRoot.getChildren().addAll(root1, root2);
    TreeView<String> tree = new TreeView<>(dummyRoot);
    tree.setShowRoot(false);
    return tree ;
}
James_D
  • 201,275
  • 16
  • 291
  • 322
  • 1
    Yes, this is a possible solution. But later it will make the code very complex. Is there any alternative solution? – Peter Penzov Mar 07 '14 at 22:49
  • yes, I made that exactly. So now, I'm wondering, is possible to set a separation between that exactly 2 nodes in the treeview?or for it I should maintain the data in 2 treeviews? – Sredny M Casanova Apr 23 '16 at 01:19
  • Found this answer today , wow James_D you saved my life again ! :) – GOXR3PLUS Sep 12 '17 at 19:38