Core Java

JavaFX TreeView Example

Photo of Andreas PomarolliAndreas PomarolliJanuary 12th, 2016Last Updated: January 11th, 2016
2 2,518 15 minutes read

This is a JavaFXTreeView example. ATreeView is a control that displays hierarchical data in a tree-like structure. Each item in aTreeView is an instance of theTreeItem class. The following example creates and displays aTreeView with different kinds of vehicles.

TheTreeView class is defined in thejavafx.scene.control package of the JavaFX API. The following examples uses Java SE 7 and JavaFX 2.2.

This article’s example is built in four steps.

  • The first example shows, how a TreeView is created
  • The second example handles TreeItem Events
  • The third example shows, how the cells in a TreeView can be editable
  • The fourth example describes, how items in a tree can be added or removed

1. The TreeViewHelper Class

This is a helper class. This:

  • Creates the Items
  • Constructs the TreeView Structure

1.1. The Code

TreeViewHelper.java

import java.util.ArrayList;import javafx.scene.control.TreeItem;public class TreeViewHelper {public TreeViewHelper(){}// This method creates an ArrayList of TreeItems (Products)public ArrayList<TreeItem> getProducts(){ArrayList<TreeItem> products = new ArrayList<TreeItem>();TreeItem cars = new TreeItem("Cars");cars.getChildren().addAll(getCars());TreeItem buses = new TreeItem("Buses");buses.getChildren().addAll(getBuses());TreeItem trucks = new TreeItem("Trucks");trucks.getChildren().addAll(getTrucks());TreeItem motorbikes = new TreeItem("Motorcycles");motorbikes.getChildren().addAll(getMotorcycles());products.add(cars);products.add(buses);products.add(trucks);products.add(motorbikes);return products;}// This method creates an ArrayList of TreeItems (Cars)private ArrayList<TreeItem> getCars(){ArrayList<TreeItem> cars = new ArrayList<TreeItem>();TreeItem ferrari = new TreeItem("Ferrari");TreeItem porsche = new TreeItem("Porsche");TreeItem ford = new TreeItem("Ford");TreeItem mercedes = new TreeItem("Mercedes");cars.add(ferrari);cars.add(porsche);cars.add(ford);cars.add(mercedes);return cars;}// This method creates an ArrayList of TreeItems (Buses)private ArrayList<TreeItem> getBuses(){ArrayList<TreeItem> buses = new ArrayList<TreeItem>();TreeItem gm = new TreeItem("GM");TreeItem vw = new TreeItem("VW");TreeItem man = new TreeItem("MAN");TreeItem volvo = new TreeItem("Volvo");buses.add(gm);buses.add(man);buses.add(volvo);buses.add(vw);return buses;}// This method creates an ArrayList of TreeItems (Trucks)private ArrayList<TreeItem> getTrucks(){ArrayList<TreeItem> trucks = new ArrayList<TreeItem>();TreeItem scania = new TreeItem("Scania");TreeItem mercedes = new TreeItem("Mercedes");TreeItem gm = new TreeItem("GM");TreeItem ford = new TreeItem("Ford");trucks.add(mercedes);trucks.add(scania);trucks.add(gm);trucks.add(ford);return trucks;}// This method creates an ArrayList of TreeItems (Motorbikes)private ArrayList<TreeItem> getMotorcycles(){ArrayList<TreeItem> motorcycles = new ArrayList<TreeItem>();TreeItem harley = new TreeItem("Harley");TreeItem suzuki = new TreeItem("Suzuki");TreeItem ktm = new TreeItem("KTM");TreeItem honda = new TreeItem("Honda");motorcycles.add(harley);motorcycles.add(honda);motorcycles.add(ktm);motorcycles.add(suzuki);return motorcycles;}}

1.2. JavaFX Classes Used for Creation of the TreeView

  • TheTreeItem class is used to construct a single node of the tree

ATreeItem is categorized as a branch or leaf node. If aTreeItem contains other instances ofTreeItem, which are called its children, it is called a branch node. Otherwise, it is called a leaf node.

1.3. Creation of the Tree

The following code creates the node cars and adds all objects, which are created by the getCars() – Method, to the node.

TreeItem cars = new TreeItem("Cars");cars.getChildren().addAll(getCars());

This part will be done also for the node buses, trucks and motorcycles. Thereafter the created nodes will be added to the root node products.

2. The JavaFX TreeView Application – Step 1

This is the main program. This:

  • Creates the Gui
  • Displays the data in the TreeView
  • Allows expanding and collapsing of the nodes

The detailed description follows the code below.

2.1 The Code

FxTreeViewExample1.java

import java.util.ArrayList;import javafx.application.Application;import javafx.stage.Stage;import javafx.scene.Scene;import javafx.scene.layout.VBox;import javafx.scene.control.TreeItem;import javafx.scene.control.TreeView;public class FxTreeViewExample1 extends Application{public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage) {// Create the TreeViewHelperTreeViewHelper helper = new TreeViewHelper();// Get the ProductsArrayList<TreeItem> products = helper.getProducts();// Create the TreeViewTreeView treeView = new TreeView();// Create the Root TreeItemTreeItem rootItem = new TreeItem("Vehicles");// Add children to the rootrootItem.getChildren().addAll(products);// Set the Root NodetreeView.setRoot(rootItem);// Create the VBoxVBox root = new VBox();// Add the TreeView to the VBoxroot.getChildren().add(treeView);// Create the SceneScene scene = new Scene(root,400,400);// Add the Scene to the Stagestage.setScene(scene);// Set the Title for the Scenestage.setTitle("TreeView Example 1");// Display the stagestage.show();}}

2.2 JavaFx Classes used for GUI

  • TheStage class constructs the main window of the application
  • TheScene class represents the visual contents of a stage
  • TheVBox class arranges its children vertically in a single column
  • TheTreeView class is used to display the data in a tree-like structure
  • TheTreeItem class is used to construct the root node of the tree

2.3 Create TreeView and Populate with data

The data will be created by using theTreeViewHelper class. The method getProducts() returns anArrayList of the classTreeItem and the structure of the tree (relations) itself:

// Create the TreeViewHelperTreeViewHelper helper = new TreeViewHelper();// Get the ProductsArrayList<TreeItem> products = helper.getProducts();

The following code creates theTreeView and it´s root node. Thereafter, the products will be added to the root node and the root node itself will be added to the tree.

// Create the TreeViewTreeView treeView = new TreeView();// Create the Root TreeItemTreeItem rootItem = new TreeItem("Vehicles");// Add children to the rootrootItem.getChildren().addAll(products);// Set the Root NodetreeView.setRoot(rootItem);

2.4 Other Properties

The following are the default properties of theTreeView:

  • The cells in a TreeView are not editable
  • The TreeView automatically provides vertical and horizontal scrollbars when needed

2.5 The Gui

Creation of a TreeView with constant data
Example of a TreeView with constant data

3. The JavaFX TreeView Application – Step 2

TheTreeView example is enhanced by handling different TreeItem-Events. ATreeItem fires events as it is modified, for example, by adding or removing children or expanding or collapsing. The following example is enriched by using thebranchExpandedEvent andbranchCollapsedEvent. Both events are instances of theTreeModificationEvent class.

3.1 The Code

FxTreeViewExample2.java

import java.util.ArrayList;import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Label;import javafx.scene.control.TextArea;import javafx.scene.control.TreeItem;import javafx.scene.control.TreeItem.TreeModificationEvent;import javafx.scene.control.TreeView;import javafx.scene.layout.VBox;import javafx.stage.Stage;import javafx.event.EventHandler;public class FxTreeViewExample2 extends Application{// Create the TextAreaprivate final TextArea textArea = new TextArea();public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage) {// Create the TreeViewHelperTreeViewHelper helper = new TreeViewHelper();// Get the ProductsArrayList<TreeItem> products = helper.getProducts();// Create the TreeViewTreeView treeView = new TreeView();// Create the Root TreeItemTreeItem rootItem = new TreeItem("Vehicles");// Add children to the rootrootItem.getChildren().addAll(products);// Set the Root NodetreeView.setRoot(rootItem);// Set tree modification related event handlers (branchExpandedEvent)rootItem.addEventHandler(TreeItem.branchExpandedEvent(),new EventHandler<TreeItem.TreeModificationEvent>(){@Overridepublic void handle(TreeModificationEvent event){branchExpended(event);}});// Set tree modification related event handlers (branchCollapsedEvent)rootItem.addEventHandler(TreeItem.branchCollapsedEvent(),new EventHandler<TreeItem.TreeModificationEvent>(){@Overridepublic void handle(TreeModificationEvent event){branchCollapsed(event);}});// Set the preferred number of text rowstextArea.setPrefRowCount(20);// Set the preferred number of text columnstextArea.setPrefColumnCount(25);// Create the VBoxVBox root = new VBox();// Add the TreeView, the Label and the TextArea to the VBoxroot.getChildren().addAll(treeView,new Label("Message Log:"), textArea);// Create the SceneScene scene = new Scene(root,400,500);// Add the Scene to the Stagestage.setScene(scene);// Set the Title for the Scenestage.setTitle("TreeView Example 2");// Display the stagestage.show();}// Helper Methods for the Event Handlersprivate void branchExpended(TreeItem.TreeModificationEvent event){String nodeValue = event.getSource().getValue().toString();this.writeMessage("Node " + nodeValue + " expanded.");}private void branchCollapsed(TreeItem.TreeModificationEvent event){String nodeValue = event.getSource().getValue().toString();this.writeMessage("Node " + nodeValue + " collapsed.");}// Method for Loggingprivate void writeMessage(String msg){this.textArea.appendText(msg + "\n");}}

3.2 Add Event Handlers for TreeItem Events

The following code adds twoEventHandler of the instanceTreeItem.TreeModificationEvent to the root node. The events are fired, if the user expands or collapse a node. The effect of these events is a logging entry in theTextArea.

// Set tree modification related event handlers (branchExpandedEvent)rootItem.addEventHandler(TreeItem.branchExpandedEvent(),new EventHandler<TreeItem.TreeModificationEvent>(){@Overridepublic void handle(TreeModificationEvent event){branchExpended(event);}});// Set tree modification related event handlers (branchCollapsedEvent)rootItem.addEventHandler(TreeItem.branchCollapsedEvent(),new EventHandler<TreeItem.TreeModificationEvent>(){@Overridepublic void handle(TreeModificationEvent event){branchCollapsed(event);}});private void branchExpended(TreeItem.TreeModificationEvent event){String nodeValue = event.getSource().getValue().toString();this.writeMessage("Node " + nodeValue + " expanded.");}private void branchCollapsed(TreeItem.TreeModificationEvent event){String nodeValue = event.getSource().getValue().toString();this.writeMessage("Node " + nodeValue + " collapsed.");}

3.3 Add a TextArea for displaying the effect of the Events Handlers

In this section aTextArea is defined for displaying the Messages of the EventHandlers.

// Create the TextAreaprivate final TextArea textArea = new TextArea();// Set the preferred number of text rowstextArea.setPrefRowCount(20);// Set the preferred number of text columnstextArea.setPrefColumnCount(25);

The following code represents the method, which displays the message in theTextArea.

// Method for Loggingprivate void writeMessage(String msg){this.textArea.appendText(msg + "\n");}

Now it is necessary, that theTextArea and aLabel will be added to theVBox.

// Add the TreeView, the Label and the TextArea to the VBoxroot.getChildren().addAll(treeView,new Label("Message Log:"), textArea);

3.4 The GUI

TreeView Example with EventHandlers
Example of a TreeView with EventHandlers

4. The JavaFX TreeView Application – Step 3

ThisTreeView example is enhanced to have editable cells.

4.1 The Code

FxTreeViewExample3.java

import java.util.ArrayList;import javafx.application.Application;import javafx.stage.Stage;import javafx.scene.Scene;import javafx.scene.layout.VBox;import javafx.scene.control.Label;import javafx.scene.control.TextArea;import javafx.scene.control.TreeItem;import javafx.scene.control.TreeView.EditEvent;import javafx.scene.control.cell.TextFieldTreeCell;import javafx.scene.control.TreeView;import javafx.event.EventHandler;public class FxTreeViewExample3 extends Application{// Create the TextAreaprivate final TextArea textArea = new TextArea();public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage) {// Create the TreeViewHelperTreeViewHelper helper = new TreeViewHelper();// Get the ProductsArrayList<TreeItem> products = helper.getProducts();// Create the TreeViewTreeView treeView = new TreeView();// Create the Root TreeItemTreeItem rootItem = new TreeItem("Vehicles");// Add children to the rootrootItem.getChildren().addAll(products);// Set the Root NodetreeView.setRoot(rootItem);// Make the TreeView editabletreeView.setEditable(true);// Set a cell factory to use TextFieldTreeCelltreeView.setCellFactory(TextFieldTreeCell.forTreeView());// Set editing related event handlers (OnEditStart)treeView.setOnEditStart(new EventHandler<TreeView.EditEvent>(){@Overridepublic void handle(EditEvent event) {editStart(event);}});// Set editing related event handlers (OnEditCommit)treeView.setOnEditCommit(new EventHandler<TreeView.EditEvent>(){@Overridepublic void handle(EditEvent event) {editCommit(event);}});// Set editing related event handlers (OnEditCancel)treeView.setOnEditCancel(new EventHandler<TreeView.EditEvent>(){@Overridepublic void handle(EditEvent event) {editCancel(event);}});// Set the preferred number of text rowstextArea.setPrefRowCount(15);// Set the preferred number of text columnstextArea.setPrefColumnCount(25);// Create the VBoxVBox root = new VBox();// Add the TreeView to the VBoxroot.getChildren().addAll(treeView,new Label("Message Log:"), textArea);// Create the SceneScene scene = new Scene(root,400,500);// Add the Scene to the Stagestage.setScene(scene);// Set the Title for the Scenestage.setTitle("TreeView Example 3");// Display the stagestage.show();}// Helper Methods for the Event Handlersprivate void editStart(TreeView.EditEvent event) {writeMessage("Started editing: " + event.getTreeItem() );}private void editCommit(TreeView.EditEvent event) {writeMessage(event.getTreeItem() + " changed." +" old = " + event.getOldValue() +", new = " + event.getNewValue());}private void editCancel(TreeView.EditEvent e) {writeMessage("Cancelled editing: " + e.getTreeItem() );}// Method for Loggingprivate void writeMessage(String msg){this.textArea.appendText(msg + "\n");}}

4.2 Editing Data in a TreeView

A cell (node) in aTreeView can be editable. An editable cell may switch between editing and nonediting mode. In editing mode, cell data can be modified by the user.TreeView has an editable property, which can be set to true using thesetEditable(true) method, as shown in the following code.

// Make the TreeView editabletreeView.setEditable(true);

4.3 Editing Data Using a TextField

ATextFieldTreeCell is rendered as aLabel in nonediting mode and as aTextField in editing mode. ItsforTreeView() static method returns a cell factory.

// Set a cell factory to use TextFieldTreeCelltreeView.setCellFactory(TextFieldTreeCell.forTreeView());

4.4 Event Handler

TreeView supports three types of events:

  • onEditStart
  • onEditCommit
  • onEditCancel

TheonEditStart event is fired when a cell enters editing mode. TheonEditCommit event is fired
when the user successfully commits the editing, for example, by pressing the Enter key in aTextField.

The following code shows an implementation of the necessary Event Handlers. In this case, a message will be written to theTextArea.

// Set editing related event handlers (OnEditStart)treeView.setOnEditStart(new EventHandler<TreeView.EditEvent>(){@Overridepublic void handle(EditEvent event) {editStart(event);}});// Set editing related event handlers (OnEditCommit)treeView.setOnEditCommit(new EventHandler<TreeView.EditEvent>(){@Overridepublic void handle(EditEvent event) {editCommit(event);}});// Set editing related event handlers (OnEditCancel)treeView.setOnEditCancel(new EventHandler<TreeView.EditEvent>(){@Overridepublic void handle(EditEvent event) {editCancel(event);}});// Helper Methods for the Event Handlersprivate void editStart(TreeView.EditEvent event) {writeMessage("Started editing: " + event.getTreeItem() );}private void editCommit(TreeView.EditEvent event) {writeMessage(event.getTreeItem() + " changed." +" old = " + event.getOldValue() +", new = " + event.getNewValue());}private void editCancel(TreeView.EditEvent e) {writeMessage("Cancelled editing: " + e.getTreeItem() );}

4.5 The Gui

Clicking a selected cell or double-clicking an unselected cell puts the cell into editing mode, which displays the cell data in aTextField.

Renaming the selected Item
Editing the selected Item

Once the cell is in editing mode, you need to click in theTextField to put the caret in theTextField so you can make changes.

Renamed the selected item
Renamed the selected item

5. The JavaFX TreeView Application – Step 4

ThisTreeView allows adding and removing nodes by the user.

5.1 The Code

FxTreeViewExample4.java

import java.util.ArrayList;import javafx.application.Application;import javafx.stage.Stage;import javafx.scene.Scene;import javafx.scene.layout.HBox;import javafx.scene.layout.VBox;import javafx.scene.control.Button;import javafx.scene.control.Label;import javafx.scene.control.TreeItem;import javafx.scene.control.TreeItem.TreeModificationEvent;import javafx.scene.control.TreeView.EditEvent;import javafx.scene.control.cell.TextFieldTreeCell;import javafx.scene.control.TreeView;import javafx.scene.control.TextArea;import javafx.scene.control.TextField;import javafx.event.ActionEvent;import javafx.event.EventHandler;public class FxTreeViewExample4 extends Application{// Create the TreeViewprivate final TreeView treeView = new TreeView();// Create the TextAreaprivate final TextArea textArea = new TextArea();// Create the TextFieldprivate TextField textField = new TextField();public static void main(String[] args){Application.launch(args);}@Overridepublic void start(Stage stage){// Create the TreeViewHelperTreeViewHelper helper = new TreeViewHelper();// Get the ProductsArrayList<TreeItem> products = helper.getProducts();// Make the TreeView editabletreeView.setEditable(true);// Set a cell factory to use TextFieldTreeCelltreeView.setCellFactory(TextFieldTreeCell.forTreeView());// Select the root nodetreeView.getSelectionModel().selectFirst();// Create the root node and adds event handler to itTreeItem rootItem = new TreeItem("Vehicles");// Add children to the rootrootItem.getChildren().addAll(products);// Set the Root NodetreeView.setRoot(rootItem);// Set editing related event handlers (OnEditStart)treeView.setOnEditStart(new EventHandler<TreeView.EditEvent>(){@Overridepublic void handle(EditEvent event){editStart(event);}});// Set editing related event handlers (OnEditCommit)treeView.setOnEditCommit(new EventHandler<TreeView.EditEvent>(){@Overridepublic void handle(EditEvent event){editCommit(event);}});// Set editing related event handlers (OnEditCancel)treeView.setOnEditCancel(new EventHandler<TreeView.EditEvent>(){@Overridepublic void handle(EditEvent event){editCancel(event);}});// Set tree modification related event handlers (branchExpandedEvent)rootItem.addEventHandler(TreeItem.branchExpandedEvent(),new EventHandler<TreeItem.TreeModificationEvent>(){@Overridepublic void handle(TreeModificationEvent event){branchExpended(event);}});// Set tree modification related event handlers (branchCollapsedEvent)rootItem.addEventHandler(TreeItem.branchCollapsedEvent(),new EventHandler<TreeItem.TreeModificationEvent>(){@Overridepublic void handle(TreeModificationEvent event){branchCollapsed(event);}});// Set tree modification related event handlers (childrenModificationEvent)rootItem.addEventHandler(TreeItem.childrenModificationEvent(),new EventHandler<TreeItem.TreeModificationEvent>(){@Overridepublic void handle(TreeModificationEvent event){childrenModification(event);}});// Create the VBoxVBox rightPane = getRightPane();// Create the HBoxHBox root = new HBox();// Set the horizontal space between each child in the HBoxroot.setSpacing(20);// Add the TreeView to the HBoxroot.getChildren().addAll(treeView,rightPane);// Create the SceneScene scene = new Scene(root,600,500);// Add the Scene to the Stagestage.setScene(scene);// Set the Title for the Scenestage.setTitle("TreeView Example 4");// Display the stagestage.show();}// This method creates a VBox and it´s components and returns it to the calling Methodprivate VBox getRightPane(){// Create the addItemBtn and its corresponding Event HandlerButton addItemBtn = new Button("Add new Item");addItemBtn.setOnAction(new EventHandler(){@Overridepublic void handle(ActionEvent event){addItem(textField.getText());}});// Create the removeItemBtn and its corresponding Event HandlerButton removeItemBtn = new Button("Remove Selected Item");removeItemBtn.setOnAction(new EventHandler(){@Overridepublic void handle(ActionEvent event){removeItem();}});// Set the preferred number of text rowstextArea.setPrefRowCount(15);// Set the preferred number of text columnstextArea.setPrefColumnCount(25);// Create the HBoxHBox hbox = new HBox();// Add Children to the HBoxhbox.getChildren().addAll(new Label("Item:"), textField, addItemBtn);// Create the VBoxVBox vbox = new VBox();// Add children to the VBoxvbox.getChildren().addAll(new Label("Select an item to add to or remove."),hbox,removeItemBtn,new Label("Message Log:"), textArea);// Set the vertical space between each child in the VBoxvbox.setSpacing(10);return vbox;}// Helper Method for Adding an Itemprivate void addItem(String value){if (value == null || value.trim().equals("")){this.writeMessage("Item cannot be empty.");return;}TreeItem parent = treeView.getSelectionModel().getSelectedItem();if (parent == null){this.writeMessage("Select a node to add this item to.");return;}// Check for duplicatefor(TreeItem child : parent.getChildren()){if (child.getValue().equals(value)){this.writeMessage(value + " already exists under " + parent.getValue());return;}}TreeItem newItem = new TreeItem(value);parent.getChildren().add(newItem);if (!parent.isExpanded()){parent.setExpanded(true);}}// Helper Method for Removing an Itemprivate void removeItem(){TreeItem item = treeView.getSelectionModel().getSelectedItem();if (item == null){this.writeMessage("Select a node to remove.");return;}TreeItem parent = item.getParent();if (parent == null ){this.writeMessage("Cannot remove the root node.");}else{parent.getChildren().remove(item);}}// Helper Methods for the Event Handlersprivate void branchExpended(TreeItem.TreeModificationEvent event){String nodeValue = event.getSource().getValue().toString();this.writeMessage("Node " + nodeValue + " expanded.");}private void branchCollapsed(TreeItem.TreeModificationEvent event){String nodeValue = event.getSource().getValue().toString();this.writeMessage("Node " + nodeValue + " collapsed.");}private void childrenModification(TreeItem.TreeModificationEvent event){if (event.wasAdded()){for(TreeItem item : event.getAddedChildren()){this.writeMessage("Node " + item.getValue() + " has been added.");}}if (event.wasRemoved()){for(TreeItem item : event.getRemovedChildren()){this.writeMessage("Node " + item.getValue() + " has been removed.");}}}private void editStart(TreeView.EditEvent event){this.writeMessage("Started editing: " + event.getTreeItem() );}private void editCommit(TreeView.EditEvent event){this.writeMessage(event.getTreeItem() + " changed." +" old = " + event.getOldValue() +", new = " + event.getNewValue());}private void editCancel(TreeView.EditEvent e){this.writeMessage("Cancelled editing: " + e.getTreeItem() );}// Method for Loggingprivate void writeMessage(String msg){this.textArea.appendText(msg + "\n");}}

5.2 Changes for the GUI

In this example we are using aHBox for the TreeView and aVBox for Buttons, Labels, etc. TheVBox represents the right Pane. There exists aButton for adding and removing an item.

// This method creates a VBox and it´s components and returns it to the calling Methodprivate VBox getRightPane(){// Create the addItemBtn and its corresponding Event HandlerButton addItemBtn = new Button("Add new Item");addItemBtn.setOnAction(new EventHandler(){@Overridepublic void handle(ActionEvent event){addItem(textField.getText());}});// Create the removeItemBtn and its corresponding Event HandlerButton removeItemBtn = new Button("Remove Selected Item");removeItemBtn.setOnAction(new EventHandler(){@Overridepublic void handle(ActionEvent event){removeItem();}});// Set the preferred number of text rowstextArea.setPrefRowCount(15);// Set the preferred number of text columnstextArea.setPrefColumnCount(25);// Create the HBoxHBox hbox = new HBox();// Add Children to the HBoxhbox.getChildren().addAll(new Label("Item:"), textField, addItemBtn);// Create the VBoxVBox vbox = new VBox();// Add children to the VBoxvbox.getChildren().addAll(new Label("Select an item to add to or remove."),hbox,removeItemBtn,new Label("Message Log:"), textArea);// Set the vertical space between each child in the VBoxvbox.setSpacing(10);return vbox;}

In the main method it is necessary to change the code as follows:

// Create the VBoxVBox rightPane = getRightPane();// Create the HBoxHBox root = new HBox();// Set the horizontal space between each child in the HBoxroot.setSpacing(20);// Add the TreeView to the HBoxroot.getChildren().addAll(treeView,rightPane);

5.3 Event Handler for Children Modification

Given the fact, that we want to add / remove items to / from the tree, we have to handle ChildrenModification-Events. The following code shows an example of anEventHandler, which handles anchildrenModificationEvent.

// Set tree modification related event handlers (childrenModificationEvent)rootItem.addEventHandler(TreeItem.childrenModificationEvent(),new EventHandler<TreeItem.TreeModificationEvent>(){@Overridepublic void handle(TreeModificationEvent event){childrenModification(event);}});private void childrenModification(TreeItem.TreeModificationEvent event){if (event.wasAdded()){for(TreeItem item : event.getAddedChildren()){this.writeMessage("Node " + item.getValue() + " has been added.");}}if (event.wasRemoved()){for(TreeItem item : event.getRemovedChildren()){this.writeMessage("Node " + item.getValue() + " has been removed.");}}}

5.4 Event Handler for Action Events

An event handler of typeActionEvent is used as a button’s action event handler. The interfaceEventHandler is implemented for this purpose. The button’s handler property is set asbutton.setOnaction. This is common for both buttons in this example – add and remove.

// Create the addItemBtn and its corresponding Event HandlerButton addItemBtn = new Button("Add new Item");addItemBtn.setOnAction(new EventHandler(){@Overridepublic void handle(ActionEvent event){addItem(textField.getText());}});// Create the removeItemBtn and its corresponding Event HandlerButton removeItemBtn = new Button("Remove Selected Item");removeItemBtn.setOnAction(new EventHandler(){@Overridepublic void handle(ActionEvent event){removeItem();}});// Helper Method for Adding an Itemprivate void addItem(String value){if (value == null || value.trim().equals("")){this.writeMessage("Item cannot be empty.");return;}TreeItem parent = treeView.getSelectionModel().getSelectedItem();if (parent == null){this.writeMessage("Select a node to add this item to.");return;}// Check for duplicatefor(TreeItem child : parent.getChildren()){if (child.getValue().equals(value)){this.writeMessage(value + " already exists under " + parent.getValue());return;}}TreeItem newItem = new TreeItem(value);parent.getChildren().add(newItem);if (!parent.isExpanded()){parent.setExpanded(true);}}// Helper Method for Removing an Itemprivate void removeItem(){TreeItem item = treeView.getSelectionModel().getSelectedItem();if (item == null){this.writeMessage("Select a node to remove.");return;}TreeItem parent = item.getParent();if (parent == null ){this.writeMessage("Cannot remove the root node.");}else{parent.getChildren().remove(item);}}

5.5 The Gui

This section shows an the following examples:

  • Adding a Nw Item to the Tree
  • Removing an existing Item from the Tree

5.5.1 Add New Items

The user navigates to the node, under which he want to add a new item (children).

Adding new Item Audi to the tree
Adding new Item Audi to the tree

He writes the name into theTextield and clicks the Add button. The action creates a newTreeItem instance and adds it to the data model. The new node is added to theTreeView.

Added new Item Audi to the tree
Added new Item Audi to the tree

5.5.2 Remove Items

The user selects the node, which he want to remove.

Removing GM from the tree
Removing GM from the tree

The user clicks the Remove Selected Item button. The action deletes the selected item from the data model and from theTreeView.

Removed GM from the tree
Removed GM from the tree

6. Download Java Source Code

This was an example ofjavafx.scene.control.TreeView

Download
You can download the full source code of this example here:JavaFxTreeViewExample.zip
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Andreas PomarolliAndreas PomarolliJanuary 12th, 2016Last Updated: January 11th, 2016
2 2,518 15 minutes read
Photo of Andreas Pomarolli

Andreas Pomarolli

Andreas has graduated from Computer Science and Bioinformatics at the University of Linz. During his studies he has been involved with a large number of research projects ranging from software engineering to data engineering and at least web engineering. His scientific focus includes the areas of software engineering, data engineering, web engineering and project management. He currently works as a software engineer in the IT sector where he is mainly involved with projects based on Java, Databases and Web Technologies.

Related Articles

Bipartite Graph

Java not equal Example

January 17th, 2020
Bipartite Graph

Java API Tutorial

October 26th, 2020
Bipartite Graph

Java Struct Example

January 8th, 2020
Bipartite Graph

Java Node Example

November 20th, 2019
Bipartite Graph

Java Swing MVC Example

January 26th, 2016
Bipartite Graph

How to call a method in Java

December 26th, 2019
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.