Answer the question
In order to leave comments, you need to log in
How not to display a directory in the TreeView that does not contain the required file?
It is necessary to search the file system for files with a certain extension and display in the form of a tree the directory in which these files are located. The code to display the entire directory was not difficult, the question is how to adapt it to the task?
Search button
@FXML
public void findInDirectory(){
DirectoryChooser directoryChooser = new DirectoryChooser();
directoryChooser.setInitialDirectory(new File(System.getProperty("user.home")));
File choice = directoryChooser.showDialog(primaryStage);
if(choice == null || ! choice.isDirectory()) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setHeaderText("Could not open directory");
alert.setContentText("The file is invalid.");
alert.showAndWait();
} else {
treeView.setRoot(getNodesForDirectory(choice));
}
}
public TreeItem<String> getNodesForDirectory(File directory) {
TreeItem<String> root = new TreeItem<>(directory.getName());
for(File f : directory.listFiles()) {
System.out.println("Loading " + f.getName());
if(f.isDirectory()) {
root.getChildren().add(getNodesForDirectory(f));
} else {
root.getChildren().add(new TreeItem<>(f.getName()));
}
}
return root;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question