How to make directories expandable in javafx TreeView
I have a problem that I'm not sure how to solve and couldn't find some clues on the internet, but the problem should be trivial ...
I have TreeView<File>
one that I would like to populate with a list of directories and files based on a given path. The problem is that directories are added to the tree, but cannot be expanded, so I cannot display the files inside.
Here is my humble controller code:
public class MainViewController implements Initializable {
@FXML // fx:id="filesTree"
private TreeView<File> filesTree;
@Override
public void initialize(URL url, ResourceBundle rb) {
File currentDir = new File("src/xslt"); // current directory
findFiles(currentDir);
}
public void findFiles(File dir) {
TreeItem<File> root = new TreeItem<>(new File("Files:"));
root.setExpanded(true);
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
System.out.println("directory:" + file.getCanonicalPath());
findFiles(file);
} else {
System.out.println(" file:" + file.getCanonicalPath());
root.getChildren().add(new TreeItem<>(file));
}
root.getChildren().add(new TreeItem<>(file));
}
filesTree.setRoot(root);
} catch (IOException e) {
e.printStackTrace();
}
}
}
And my presentation is FXML
really simple - just AnchorPane
with TreeView
. But I can share it if necessary.
So the questions are: How do you make directories extensible? I found a method setExpanded(true)
, but this is different.
source to share
Basically, the recursive method should create a new root every time you find a directory.
private void findFiles(File dir, TreeItem<File> parent) {
TreeItem<File> root = new TreeItem<>(dir);
...
}
And this one root
should be sent as parent for the next level.
if (file.isDirectory()) {
System.out.println("directory:" + file.getCanonicalPath());
findFiles(file,root);
}
Finally, just at the very top level, we set this root as root from treeView:
if(parent==null){
filesTree.setRoot(root);
}
and at the internal levels:
else {
parent.getChildren().add(root);
}
So, after these few adjustments, this should work:
@FXML private TreeView<File> filesTree;
@Override
public void initialize(URL url, ResourceBundle rb) {
File currentDir = new File("src/xslt"); // current directory
findFiles(currentDir,null);
}
private void findFiles(File dir, TreeItem<File> parent) {
TreeItem<File> root = new TreeItem<>(dir);
root.setExpanded(true);
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
System.out.println("directory:" + file.getCanonicalPath());
findFiles(file,root);
} else {
System.out.println(" file:" + file.getCanonicalPath());
root.getChildren().add(new TreeItem<>(file));
}
}
if(parent==null){
filesTree.setRoot(root);
} else {
parent.getChildren().add(root);
}
} catch (IOException e) {
e.printStackTrace();
}
}
source to share