Reputation: 550
To make it clear, I'm creating a treeview that will instantiate itself after the user creates a folder and said folder will be added as treeitem.
I currently have this:
TreeView treeView = new TreeView();
// Create new folder
MenuItem menuItem1 = new MenuItem("Create New Folder");
menuItem1.setOnAction(e -> {
System.out.println("Please name your directory:");
Scanner in = new Scanner(System.in);
String strFolder = in. nextLine();
createFolder(strFolder); // Create folder
TreeItem rootFolder = new TreeItem(strFolder); // Create new TreeItem
treeView.setRoot(rootFolder); // Replace old folder with new one
// rootFolder.getChildren().add(rootFolder);
// rootItem.getChildren().add(rootFolder);
});
After the treeView, I declared a new Menu Item that which will trigger an event after being clicked on.
The event will ask the user for a name to use as the root folder for the treeView. Now thats working fine.
Now what I'm having troubles with, is how to create more folders inside the root folder created and display them as subfolders in the treeView?
So far my code only does replace the old root folder by the new one created. Instead of setting the root folder again, how can i make it so it just adds those folders inside the first one and display them - again - in the treeView as subfolders?
Did I explain myself?
Thanks.
Upvotes: 0
Views: 97
Reputation: 82461
Simply add TreeItem
(s) to the child list of the TreeItem
. The following example replaces the root, if no items are selected and otherwise adds the new item as a child of the selected one:
TreeView<String> treeView = new TreeView<>(); // never use raw type without good reason
// Create new folder
MenuItem menuItem1 = new MenuItem("Create New Folder");
menuItem1.setOnAction(e -> {
TextInputDialog dialog = new TextInputDialog(); // replacing console input with dialog here
dialog.setHeaderText("Please name your directory:");
String strFolder = dialog.showAndWait().orElse(null);
if (strFolder != null) {
TreeItem<String> newFolder = new TreeItem<>(strFolder); // Create new TreeItem
TreeItem<String> selection = treeView.getSelectionModel().getSelectedItem();
createFolder(strFolder); // Create folder ; TODO: make dependent on parent???
if (selection == null) {
treeView.setRoot(newFolder); // Replace old folder with new one
} else {
selection.getChildren().add(newFolder);
selection.setExpanded(true); // make sure we're able to see the new child
}
}
});
Upvotes: 1