Armand Delessert Armand Delessert - 3 months ago 23x
Java Question

Remove a node without knowing the parent (JavaFX)

Can I remove a node from a scene without knowing the parent?

In others words, can I do something like this:

@FXML private ToolBar toolBar;

protected void handleCloseButtonAction(ActionEvent actionEvent) {


If I do this, it throws a


You get the exception, because getChildrenUnmodifiable returns a read-only list:

Gets the list of children of this Parent as a read-only list.

It's always better and safer if you store the reference of the parent container, but theoretically you can do it by casting the Parent object returned by the getParent() method to the type of the parent container.

For example if the ToolBar is added to a VBox:

((VBox) toolBar.getParent()).getChildren().remove(toolBar);

Or, if you want to be a little bit more generic, you can cast it to a Pane, as it is the super class for a lots of containers:

((Pane) toolBar.getParent()).getChildren().remove(toolBar);

Still, I would suggest to store the reference of the parent container instead of doing one of these (or similar).