How to display only the filename in a JavaFX TreeView?

你说的曾经没有我的故事 提交于 2020-07-30 04:20:16

问题


So i have figured out how to get all the files and directories and add them to the treeview but it shows me the complete file path: C/user/file.txt i just want the file or folder name and not the path.

The code to create the list is as follows:

private TreeItem<File> buildFileSys(File dir, TreeItem<File> parent){
    TreeItem<File> root = new TreeItem<>(dir);
    root.setExpanded(false);
    File[] files = dir.listFiles();
    for (File file : files) {
        if (file.isDirectory()) {
            buildFileSys(file,root);
        } else {
            root.getChildren().add(new TreeItem<>(file));
        }

    }
    if(parent==null){
        return root;
    } else {
        parent.getChildren().add(root);
    }
    return null;
}

I then take the returned TreeItem and do treeview.setroot(treeItem< File> obj);

Any help would be greatly appreciated.


回答1:


Use a custom cellFactory to determine, how the items are shown in the TreeView:

treeView.setCellFactory(new Callback<TreeView<File>, TreeCell<File>>() {

    public TreeCell<File> call(TreeView<File> tv) {
        return new TreeCell<File>() {

            @Override
            protected void updateItem(File item, boolean empty) {
                super.updateItem(item, empty);

                setText((empty || item == null) ? "" : item.getName());
            }

        };
    }
});


来源:https://stackoverflow.com/questions/44210453/how-to-display-only-the-filename-in-a-javafx-treeview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!