package tests; import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.input.MouseEvent; import javafx.stage.Stage; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author sjiang */ public class MyTreeViewTest extends Application { public static void main(String[] args) throws Exception { Application.launch(args); } @Override public void start(Stage stage) throws Exception { final TreeView treeView = new TreeView(); treeView.setPrefSize(300, 300); TreeItem root = new TreeItem("Root"); root.setExpanded(true); addChildren(root, "child1"); treeView.setRoot(root); for (TreeItem ti : root.getChildren()) { addChildren(ti, "child2"); } final TreeItem selected = root.getChildren().get(0).getChildren().get(0); treeView.getSelectionModel().select(selected); System.out.println("---The selected item is: "+selected.getValue()); treeView.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler() { @Override public void handle(MouseEvent me) { checkSelection(treeView, selected); } }); Scene scene = new Scene(treeView); stage.setScene(scene); stage.setVisible(true); } private static void checkSelection(TreeView treeView, TreeItem selected) { if (treeView.getSelectionModel().getSelectedItems().size() == 1 && treeView.getSelectionModel().getSelectedItems().get(0) == selected) { System.out.println("---The selection is correct!"); } else { throw new RuntimeException("Wrong selection: expected: "+selected.getValue()+" but got "+treeView.getSelectionModel().getSelectedItems()); } } private static void addChildren(TreeItem parent, String name) { for (int i=0; i<3; i++) { TreeItem ti = new TreeItem(name+"-"+i); parent.getChildren().add(ti); } } }