user1673554
user1673554

Reputation: 461

Creating a JavaFX TreeView using Scene Builder

I'm starting working with JavaFX and wish to use the new tree view (as you can use multiple icons to represent your data - which is what I wish to take advantage of).

I have created a basic form/scene that has a tree view and one button on it. When this button is pressed I wish to populate the treeview.

Now, all the examples ive looked at are where the form/scene is generated in code and the treeview is bound to that control....how do I have a pre designed form with Scene builder and populate it from external code?

Upvotes: 3

Views: 13812

Answers (2)

Kevin Kabatra
Kevin Kabatra

Reputation: 122

You could use the following code in a controller class. Inside the FXML file you will need to set the FXID to selectionTreeView. Tested in JDK 8u5 and it worked.

@FXML
TreeView selectionTreeView;
@FXML
private void handleButtonAction(ActionEvent event) {
    createTree();
}

public void createTree(String... rootItems) {
    //create root
    TreeItem<String> root = new TreeItem<>("Root");
    //root.setExpanded(true);
    //create child
    TreeItem<String> itemChild = new TreeItem<>("Child");
    itemChild.setExpanded(false);
    //root is the parent of itemChild
    root.getChildren().add(itemChild);
    selectionTreeView.setRoot(root);
}

Upvotes: 3

Andy Till
Andy Till

Reputation: 3511

Set the class name (including package) on the root node of your control in scene builder. If you click on, then go to the code tab on the right it is the top field.

Now set an ID on the TreeView in your control.

Now in the controller object add a TreeView field, the variable name should be the same as what you set the TreeView ID as in scene builder. Annotate with field with @FXML.

Now when the FXML is loaded, the controller is created and the TreeView field is set.

Upvotes: 0

Related Questions