package tests; import java.util.ArrayList; import java.util.List; import javafx.application.Application; import javafx.collections.ObservableList; 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<String> root = new TreeItem<String>("Root"); root.setExpanded(true); addChildren(root, "child1"); treeView.setRoot(root); for (TreeItem<String> 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<MouseEvent>() { @Override public void handle(MouseEvent me) { if (!treeView.getSelectionModel().getSelectedItems().isEmpty()) { change(((TreeItem)treeView.getSelectionModel().getSelectedItems().get(0))); } } }); Scene scene = new Scene(treeView); stage.setScene(scene); stage.setVisible(true); } private static void change(TreeItem child) { TreeItem parent = child.getParent(); System.out.println("\n---change for parent "+parent+" "+child); if (parent != null) { ObservableList children = parent.getChildren(); List list = new ArrayList(children); if (!list.isEmpty()) { int at = children.size()-1; TreeItem removed = (TreeItem)list.remove(at); System.out.println("---change removed "+removed+" at "+at); list.add(0, removed); parent.getChildren().setAll(list); } } } 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<String> ti = new TreeItem<String>(name+"-"+i); parent.getChildren().add(ti); } } }