Monday, 18 June 2018

JavaFX: TreeView: Add new tree items to tree

In my previous post, I explained how to edit the tree item using custom cell factory. In this post, I am going to show you how to add new tree item to the tree.

This is continuation to my previous post (I am extending the same application developed in previous post).

Step 1: Create a menu item to display the ‘add Faculty’ button.

MenuItem addMenuItem = new MenuItem("Add Faculty");
addFaculty.getItems().add(addMenuItem);
addMenuItem.setOnAction((ActionEvent t) -> {
         TreeItem<String> newFaculty = new TreeItem<>("New Faculty");
         getTreeItem().getChildren().add(newFaculty);
});

Step 2: Add this menu item, when user press right click.

if (!getTreeItem().isLeaf() && getTreeItem().getParent() != null) {
         setContextMenu(addFaculty);
}

Find the below working application.

TreeCellTextField.java

package com.sample.demos;

import javafx.event.ActionEvent;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

public class TreeCellTextField extends TreeCell<String> {
 private TextField textField;
 private final ContextMenu addFaculty = new ContextMenu();

 public TreeCellTextField() {
  MenuItem addMenuItem = new MenuItem("Add Faculty");
  addFaculty.getItems().add(addMenuItem);
  addMenuItem.setOnAction((ActionEvent t) -> {
   TreeItem<String> newFaculty = new TreeItem<>("New Faculty");
   getTreeItem().getChildren().add(newFaculty);
  });
 }

 /**
  * On editing, create new text field and set it using setGraphic method.
  */
 @Override
 public void startEdit() {
  super.startEdit();

  if (textField == null) {
   createTextField();
  }
  setText(null);
  setGraphic(textField);
  textField.selectAll();
 }

 /**
  * On cancel edit, set the original content back
  */
 @Override
 public void cancelEdit() {
  super.cancelEdit();
  setText((String) getItem());
  setGraphic(getTreeItem().getGraphic());
 }

 @Override
 public void updateItem(String item, boolean empty) {
  super.updateItem(item, empty);

  if (empty) {
   setText(null);
   setGraphic(null);
   return;
  }

  if (!isEditing()) {
   setText(getString());
   setGraphic(getTreeItem().getGraphic());

   if (!getTreeItem().isLeaf() && getTreeItem().getParent() != null) {
    setContextMenu(addFaculty);
   }

   return;
  }

  if (textField != null) {
   textField.setText(getString());
  }
  setText(null);
  setGraphic(textField);

 }

 private void createTextField() {
  textField = new TextField(getString());
  textField.setOnKeyReleased((KeyEvent t) -> {
   if (t.getCode() == KeyCode.ENTER) {
    commitEdit(textField.getText());
   } else if (t.getCode() == KeyCode.ESCAPE) {
    cancelEdit();
   }
  });
 }

 private String getString() {
  return getItem() == null ? "" : getItem().toString();
 }
}

TreeViewApp.java
package com.sample.demos;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.StackPane;
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<>("College");
  rootItem.setExpanded(true);

  /* Defile 1st level child items */
  TreeItem<String> physicsDepartment = new TreeItem<>("Physics Department");
  TreeItem<String> chemistryDepartment = new TreeItem<>("Chemistry Department");
  TreeItem<String> mathsDepartment = new TreeItem<>("Maths Department");

  /* Add items to root item */
  rootItem.getChildren().addAll(physicsDepartment, chemistryDepartment, mathsDepartment);

  /* Adding Physics faculty details to physics department */
  TreeItem<String> physicsFaculty1 = new TreeItem<>("Srinivasa Rao");
  TreeItem<String> physicsFaculty2 = new TreeItem<>("Madavi Latha");
  physicsDepartment.getChildren().addAll(physicsFaculty1, physicsFaculty2);
  physicsDepartment.setExpanded(true);

  /* Adding chemistry faculty details to physics department */
  TreeItem<String> chemistryFaculty1 = new TreeItem<>("Naga Veni");
  TreeItem<String> chemistryFaculty2 = new TreeItem<>("Raghava Rao");
  chemistryDepartment.getChildren().addAll(chemistryFaculty1, chemistryFaculty2);
  chemistryDepartment.setExpanded(true);

  /* Adding maths faculty details to maths department */
  TreeItem<String> mathsFaculty1 = new TreeItem<>("Venkata Anjaneyulu");
  TreeItem<String> mathsFaculty2 = new TreeItem<>("Rama Krishna");
  mathsDepartment.getChildren().addAll(mathsFaculty1, mathsFaculty2);
  mathsDepartment.setExpanded(true);

  TreeView<String> treeView = new TreeView<>(rootItem);
  treeView.setEditable(true);
  treeView.setCellFactory((TreeView<String> p) -> new TreeCellTextField());

  StackPane stackPane = new StackPane();
  stackPane.getChildren().add(treeView);

  primaryStage.setScene(new Scene(stackPane));
  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);
 }
}


After adding new faculty to ‘Physics Department’ the tree changed like below.




Previous                                                 Next                                                 Home

No comments:

Post a Comment