JavaFX - TreeView



The TreeView is a graphical user interface component that displays a hierarchical structure of items. It consists of a root node and any number of child nodes. Primarily, the tree view is used for organizing data with hierarchy. It provides a better understanding of data and its relation with other components. In the below figure, we can see a tree view of components.

TreeView

TreeView in JavaFX

In JavaFX, the treeview is represented by a class named TreeView. This class belongs to the package javafx.scene.control. By instantiating this class, we can create a treeview in JavaFX. Constructors of the TreeView class are listed below −

  • TreeView() − It is the default constructor that constructs an empty treeview.

  • TreeView(TreeItem rootNode) − It creates a new treeview with the specified root node.

How to create a TreeView in JavaFX?

Follow the steps given below to create a tree view in JavaFX.

Step 1: Create the root node of TreeView

First, create containers for the lists of all items. In this case, root node is the container as it holds all the child nodes. To create the root node, we use the TreeItem class which is the part of javafx.scene.control package. Pass the name of root node to the constructor of this class as a parameter value. −

// Creating the root node
TreeItem<String> root = new TreeItem<>("Smartphones");

Step 2: Create the child nodes of TreeView

Again, use the TreeItem class to create child nodes. Once the child nodes are created, use the getChildren() method along with addAll() to add the required items to it.

TreeItem<String> ios = new TreeItem<>("iOS");
ios.getChildren().addAll(
   new TreeItem<>("iPhone 15 Plus"),
   new TreeItem<>("iPhone 14")
);

Step 3: Add the child nodes to root nodes

To add the child nodes to the root node, pass the name of child nodes as a parameter value to the addAll() method as shown in the following code blocks −

// Add the child nodes to the root node
root.getChildren().addAll(android, ios);

Step 4: Instantiate the TreeView class

To create tree view, instantiate the TreeView class and pass the root node to its constructor as a parameter value as shown in the below code −

// Create the TreeView and add the root node
TreeView<String> treesV = new TreeView<>(root);

Step 5: Launching Application

Once the tree view is created, follow the given steps below to launch the application properly −

  • Firstly, instantiate the class named Scene by passing the TreeView object as a parameter value to its constructor. We can also pass the dimensions of the application screen as optional parameters to this constructor.

  • Then, set the title to the stage using the setTitle() method of the Stage class.

  • Now, a Scene object is added to the stage using the setScene() method of the class named Stage.

  • Display the contents of the scene using the method named show().

  • Lastly, the application is launched with the help of the launch() method.

Example

Following is the program that will create a TreeView using JavaFX. Save this code in a file with the name JavafxTreeview.java.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.stage.Stage;
public class JavafxTreeview extends Application {
   @Override
   public void start(Stage stage) throws Exception {
      // Creating the root node
      TreeItem<String> root = new TreeItem<>("Smartphones");
      root.setExpanded(true);
      // Creating its child nodes
      TreeItem<String> android = new TreeItem<>("Android");
      android.getChildren().addAll(
         new TreeItem<>("Samsung Galaxy S23 Ultra"),
         new TreeItem<>("Xiaomi Redmi Note 13 Pro"),
         new TreeItem<>("OnePlus 11R")
      );
      TreeItem<String> ios = new TreeItem<>("iOS");
      ios.getChildren().addAll(
         new TreeItem<>("iPhone 15 Plus"),
         new TreeItem<>("iPhone 14")
      );
      // Add the child nodes to the root node
      root.getChildren().addAll(android, ios);
      // Create the TreeView and add the root node
      TreeView<String> treesV = new TreeView<>(root);
      // Create a scene and add the TreeView
      Scene scene = new Scene(treesV, 400, 300);
      stage.setTitle("TreeView in JavaFX");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String[] args) {
      launch(args);
   }
}

Compile and execute the saved Java file from the command prompt using the following commands −

javac --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxTreeview.java
java --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxTreeview

Output

On executing, the above program generates a JavaFX window displaying a TreeView with a list of smartphones as shown below.

Treeview Output

Setting the mouse events for TreeView

If we want to show which items are getting clicked by users, then, we can use setOnMouseClicked() method by passing a lambda expression as shown in the below JavaFX code. Save this code in a file with the name JavafxTreeview.java.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.stage.Stage;
public class JavafxTreeview extends Application {
   @Override
   public void start(Stage stage) throws Exception {
      // Creating the root node
      TreeItem<String> root = new TreeItem<>("Smartphones");
      root.setExpanded(true);
      // Creating its child nodes
      TreeItem<String> android = new TreeItem<>("Android");
      android.getChildren().addAll(
         new TreeItem<>("Samsung Galaxy S23 Ultra"),
         new TreeItem<>("Xiaomi Redmi Note 13 Pro"),
         new TreeItem<>("OnePlus 11R")
      );
      TreeItem<String> ios = new TreeItem<>("iOS");
      ios.getChildren().addAll(
         new TreeItem<>("iPhone 15 Plus"),
         new TreeItem<>("iPhone 14")
      );
      // Add the child nodes to the root node
      root.getChildren().addAll(android, ios);
      // Create the TreeView and add the root node
      TreeView<String> treesV = new TreeView<>(root);
      // Handle mouse clicks on the nodes
      treesV.setOnMouseClicked(event -> {
         // Get the selected item
         TreeItem<String> item = treesV.getSelectionModel().getSelectedItem();
         if (item != null) {
            // Display the item text
            System.out.println(item.getValue());
         }
      });
      // Create a scene and add the TreeView
      Scene scene = new Scene(treesV, 400, 300);
      stage.setTitle("TreeView in JavaFX");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String[] args) {
      launch(args);
   }
}

To compile and execute the saved Java file from the command prompt, use the following commands −

javac --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxTreeview.java
java --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxTreeview

Output

On executing the above code, it will generate the following output. When we click on the items, their name will be displayed on the console.

Treeview Output2
Advertisements