How to delete a specific TreeItem from the TreeView in javafx?

I’ve got a TreeView called foodTree to which I’ve added some TreeItem. The code :

import javafx.application.Application ; import javafx.scene.Scene ; import javafx.event.* ; import javafx.stage.* ; import javafx.scene.layout.* ; import javafx.scene.control.* ; import javafx.geometry.* ; import javafx.scene.control.cell.PropertyValueFactory ; import javafx.collections.* ;  public class Tree extends Application {     TreeView foodTree ;      public static void main(String[] args)      {         Application.launch(args) ;     }      @Override     public void start(Stage window)     {         TreeItem<String> root, vegetables, fruits ;          root = new TreeItem<>() ;         root.setExpanded(true) ;          vegetables = makeBranch("Vegies", root) ;         makeBranch("Cabbage", vegetables) ;         makeBranch("Beans", vegetables) ;          fruits = makeBranch("Fruits", root) ;         makeBranch("Apples", fruits) ;         makeBranch("Mangoes", fruits) ;          foodTree = new TreeView<>(root) ;         foodTree.setShowRoot(false) ;         foodTree.setPrefWidth(180) ;         foodTree.setMaxSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE) ;          BorderPane b_pane = new BorderPane() ;         b_pane.setLeft(foodTree) ;          Scene scene = new Scene(b_pane, 300, 200) ;          window.setScene(scene) ;         window.show() ;     }      public TreeItem<String> makeBranch(String title, TreeItem<String> parent)      {         TreeItem<String> item = new TreeItem<>(title) ;         item.setExpanded(false) ;          parent.getChildren().add(item) ;          return item ;     }    } 

I wish to know how to delete a TreeItem from the TreeView – how can I delete Mangoes so that it’s not displayed in the TreeView?

Add Comment
1 Answer(s)

To remove a tree item, you need to remove it from the list returned by its parent’s getChildren() method. If you have a reference to the item to be removed, this is straightforward. For example, if you do

// makeBranch("Mangoes", fruits) ; TreeItem<String> mangoes = makeBranch("Mangoes", fruits) ; 

then later you can simply remove the item from its parent:

mangoes.getParent().getChildren().remove(mangoes); 

In this case, since you know the parent, you could also just do

fruits.getChildren().remove(mangoes); 

You can also use any of the standard methods defined in List on the parent’s getChildren(), e.g.

// remove any items from fruits whose value is "Mangoes": fruits.getChildren().removeIf(treeItem -> treeItem.getValue().equals("Mangoes")); // remove the first child from fruits: fruits.getChildren().remove(0); 
Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.