B4J Question Example of a TreeView in Java

Sergey_New

Well-Known Member
Licensed User
Longtime User
I give an example of a TreeView in Java.
B4X:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;

public class TreeViewMain extends Application {
    @Override
    public void start(Stage stage) throws IOException {

        File filePath = new File("D:\\IDEA Projects"); // you can change the path here to your desired path
        
        // Create the root and items
        TreeItem<String> root = createItems(filePath);

        // create the treeview
        TreeView<String> treeView = new TreeView<>(root);

        // Create the Scene and show the stage
        VBox layout = new VBox(treeView);
        Scene scene = new Scene(layout, 400, 400);
        stage.setScene(scene);
        stage.setTitle("JavaFX TreeView");
        stage.show();

        // This code will print out the selected items on the TreeView
        treeView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue ) ->{
            String selectedItem = newValue.getValue();
            System.out.println(selectedItem);
        });
    }

    // create the treeitems dynamically based on the given path
    private TreeItem<String> createItems(File file){
        TreeItem<String> treeItems = new TreeItem<>(file.getName());
        if(file.isDirectory()){
            File[] files = file.listFiles();
            if(files != null){
                for(File childItem : files){
                    treeItems.getChildren().addAll(createItems(childItem));
                }
            }
        }

        return treeItems;
    }

    public static void main(String[] args) {
        launch();
    }
}
Please create this example using B4J.
 
Top