在不知道父节点的情况下删除节点(JavaFX)

Jea*_*kow 1 java javafx fxml

我可以在Node不知道其父级的情况下从场景图中删除a 吗?

换句话说,我可以这样做吗?

@FXML private ToolBar toolBar;

@FXML
protected void handleCloseButtonAction(ActionEvent actionEvent) {
    toolBar.getParent().getChildrenUnmodifiable().remove(toolBar);

    actionEvent.consume();
}
Run Code Online (Sandbox Code Playgroud)

如果我这样做,它会抛出一个java.lang.UnsupportedOperationException.

DVa*_*rga 6

您将获得UnsupportedOperationException,因为它Parent#getChildrenUnmodifiable返回一个只读列表:

获取此Parent的子项列表作为只读列表.

如果存储父容器的引用,它总是更好更安全,但理论上你可以通过(向下)ParentgetParent()方法返回的对象转换为父容器的类型来实现.

例如,如果将ToolBar其添加到VBox:

((VBox) toolBar.getParent()).getChildren().remove(toolBar);
Run Code Online (Sandbox Code Playgroud)

或者,如果您想要更通用一些,可以将返回的父级转换为Paneafter类型检查,因为此类是JavaFX容器的超类,它允许修改子列表:

if (toolBar.getParent() instanceof Pane)   
    ((Pane) toolBar.getParent()).getChildren().remove(toolBar);
Run Code Online (Sandbox Code Playgroud)

不过,我建议存储父容器的引用,而不是遵循这些(或类似的)方法之一,因为这不是一个干净的,并且因为向下转换不是一个安全的解决方案(没有类型检查).