0

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

1 Answer 1

4

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()); } }; } }); 
Sign up to request clarification or add additional context in comments.

3 Comments

Hey thank you for the solution but i am getting an error: Type mismatch: cannot convert from new TreeCell<File>(){} to TreeCell<File>
@Reggie: I overlooked the javafx-2 tag. You're probably using java 7 so lambdas are not allowed of course. (Should be fixed now.) Otherwise there is a issue with the type parameter of TreeView or with your imports...
Could you please add an explanation as to what it is the code does if possible. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.