JavaFX TreeView


JavaFX TreeView tutorials:

The TreeView is a way to represent a structure in the tree form which contains root, childes and sub-childes.
By using treeview it is possible to go down into children of a TreeItem until a TreeItem has no children(leaf).

Constructors of TreeView :

  • TreeView()
    Creates an empty TreeView.
  • TreeView(TreeItem<T> root)
    Creates a TreeView with the provided root node.

Creation of TreeView :

  • To create a TreeView we use the TreeItem class AS
    TreeItem<String> root = new TreeItem<String>(“Root Node”);
  • Use setExpanded() method to set it pre(when load) expanded or not.
  • And make other treeitem to add children.
  • And finally add root(TreeItem) to TreeView AS
    TreeView<String> treeView = new TreeView<String>(root);

Example of tree view:

package javafxtuts;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.stage.Stage;

 * @author javafxtuts
public class Javafxtuts extends Application {
    public static final String Column1MapKey = "A";
    public static final String Column2MapKey = "B";
    public static void main(String[] args) {
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Table View Sample");
        //to create a root(tree root)
       TreeItem titem=new TreeItem("JavaFX");
       //to set it expanded when it loaded
       //creating children for root
       TreeItem titem1=new TreeItem("UI COntrols");
       TreeItem titem12=new TreeItem("tree view");
       TreeItem titem2=new TreeItem("Layout");
       //to add children to the titem1
       //to add children to the titem
       //to create a TreeView of titem
       TreeView tview=new TreeView(titem);
        //to create a scene using tview
      Scene scene = new Scene(tview, 250, 300);


Output :

Explanation of tree view example :

  • To create a root node(A tree root) using TreeItem class we create item of tree AS
    TreeItem titem=new TreeItem("JavaFX");
  • Create more items using TreeItem class for children of root node (titem) AS
    TreeItem titem1=new TreeItem("UI Controls");
  • Adding children to the titem1(child of root node) AS
  • To add children to the titem
  • And finally create a TreeView and add titem AS
    TreeView tview=new TreeView(titem);

Leave A Reply