问题
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