Monday 18 June 2018

JavaFX: TreeView: Create Tree Views

Below step-by-step procedure explains how to create tree views in javafx.

Step 1: Define root item object.
TreeItem<String> rootItem = new TreeItem<> ("Root");

Step 2: Define child items.
TreeItem<String> level1Item1 = new TreeItem<> ("Level1_Child1");
TreeItem<String> level1Item2 = new TreeItem<> ("Level1_Child2");
TreeItem<String> level1Item3 = new TreeItem<> ("Level1_Child3");

Step 3: Add child items to the root item.
rootItem.getChildren().addAll(level1Item1, level1Item2, level1Item3);

Step 4: Add the root item to the TreeView.
TreeView<String> treeView = new TreeView<> (rootItem);

Find the below working application.

TreeViewApp.java
package com.sample.demos;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class TreeViewApp extends Application {

 @SuppressWarnings("unchecked")
 @Override
 public void start(Stage primaryStage) throws Exception {
  /* Define Root Item */
  TreeItem<String> rootItem = new TreeItem<>("Root");

  /* Defile 1st level child items */
  TreeItem<String> level1Item1 = new TreeItem<>("Level1_Child1");
  TreeItem<String> level1Item2 = new TreeItem<>("Level1_Child2");
  TreeItem<String> level1Item3 = new TreeItem<>("Level1_Child3");

  /* Add items to root item */
  rootItem.getChildren().addAll(level1Item1, level1Item2, level1Item3);

  TreeItem<String> level2Item1 = new TreeItem<>("Level2_Child1");
  TreeItem<String> level2Item2 = new TreeItem<>("Level2_Child1");
  level1Item1.getChildren().addAll(level2Item1, level2Item2);

  TreeView<String> treeView = new TreeView<>(rootItem);

  VBox vBox = new VBox(10, treeView);
  vBox.setSpacing(5);
  vBox.setPadding(new Insets(10, 10, 10, 10));

  primaryStage.setScene(new Scene(vBox));
  primaryStage.setTitle("Tree View Example");
  primaryStage.setWidth(900);
  primaryStage.setHeight(500);
  primaryStage.show();
 }

}

TestFX.java
package com.sample.demos;

import javafx.application.Application;

public class TestFX {
 public static void main(String args[]) {
  Application.launch(TreeViewApp.class, args);
 }
}




 Expand the item Root, you can able to see the tree structure like below.


Expand ‘Level1_Child1’.


Previous                                                 Next                                                 Home

No comments:

Post a Comment