如何使用JavaFX创建TreeView?
一棵树提供了层次结构的视图,每棵树都包含一个根(最高对象)并且包含子级。您可以通过实例化javafx.scene.control.TreeView 类来创建树视图。
示例
以下示例演示了TreeView的创建。
import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage; public class TreeViewExample extends Application { public void start(Stage stage) { //创建树项 TreeItem root1 = new TreeItem("Programming Languages"); TreeItem item1 = new TreeItem("Java"); TreeItem item2 = new TreeItem("Python"); TreeItem item3 = new TreeItem("C++"); //将元素添加到root1- root1.getChildren().addAll(item1, item2, item3); TreeItem root2 = new TreeItem("NoSQL Databases"); TreeItem item4 = new TreeItem("Neo4j"); TreeItem item5 = new TreeItem("HBase"); TreeItem item6 = new TreeItem("Cassandra"); //将元素添加到root2- root2.getChildren().addAll(item4, item5, item6); TreeItem root3 = new TreeItem("Bigdata & Analytics"); TreeItem item7 = new TreeItem("Hadoop"); TreeItem item8 = new TreeItem("Mahout"); TreeItem item9 = new TreeItem("Hive"); //将元素添加到root2- root3.getChildren().addAll(item7, item8, item9); //列表查看学历 TreeItem<String> base = new TreeItem<String>("Technologies"); base.setExpanded(true); base.getChildren().addAll(root1, root2, root3); //创建一个TreeView项目 TreeView view = new TreeView(base); view.setPrefHeight(300); VBox pane = new VBox(10); pane.setPadding(new Insets(5, 5, 5, 50)); pane.getChildren().addAll(view); //设置舞台 Group node = new Group(pane); Scene scene = new Scene(node, 595, 320, Color.BEIGE); stage.setTitle("List View Example"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
输出结果