/* * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. */ package helloworld; import java.io.File; import javafx.application.Application; import javafx.application.Launcher; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.paint.Color; import javafx.stage.Stage; import com.javafx.preview.control.TreeView; import com.sun.javafx.Utils; import javafx.scene.control.model.TreeNode; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javafx.scene.Group; public class HelloTreeViewFileSystem extends Application { public static void main(final String[] args) { Launcher.launch(HelloTreeViewFileSystem.class, args); } @Override public void start(Stage stage) { stage.setTitle("Hello FileSystem TreeView"); final Scene scene = new Scene(new Group(), 800, 600); scene.setFill(Color.LIGHTGRAY); final Label label = new Label("FileSystem TreeView:"); label.setLayoutX(25); label.setLayoutY(20); ((Group)scene.getRoot()).getChildren().add(label); TreeNode root = null; if (Utils.isWindows()) { root = createNode(new File("c:/")); } else { root = createNode(new File("/")); } final TreeView treeView = new TreeView(); treeView.setShowRoot(true); treeView.setRoot(root); treeView.setLayoutX(25); treeView.setLayoutY(40); treeView.setPrefSize(720, 500); ((Group)scene.getRoot()).getChildren().add(treeView); stage.setScene(scene); stage.setVisible(true); } private TreeNode createNode(final File f) { final TreeNode node = new TreeNode(f); node.setChildBuilder(new TreeNode.ChildBuilder() { private boolean isLeaf; private boolean isFirstTime = true; public List> build(TreeView.TreeElement treeNode) { System.out.println("build children for " + f); return buildChildren(treeNode); } public boolean isLeaf(TreeView.TreeElement treeNode) { if (isFirstTime) { File f = (File) treeNode.getValue(); // System.out.println("is leaf: " + f); isLeaf = f.isFile(); isFirstTime = false; } return isLeaf; } }); return node; } private List> buildChildren(TreeView.TreeElement treeNode) { File f = (File) treeNode.getValue(); if (f != null && f.isDirectory()) { File[] files = f.listFiles(); if (files != null) { List> children = new ArrayList>(files.length); for (File childFile : files) { TreeNode child = createNode(childFile); children.add(child); } return children; } } return Collections.emptyList(); } }