在不知道父节点的情况下删除节点 (JavaFX)
Remove a node without knowing the parent (JavaFX)
我可以在不知道父级的情况下从场景图中删除 Node
吗?
换句话说,我可以做这样的事情吗?
@FXML private ToolBar toolBar;
@FXML
protected void handleCloseButtonAction(ActionEvent actionEvent) {
toolBar.getParent().getChildrenUnmodifiable().remove(toolBar);
actionEvent.consume();
}
如果我这样做,它会抛出 java.lang.UnsupportedOperationException
.
您得到 UnsupportedOperationException, because Parent#getChildrenUnmodifiable
returns 一个只读列表:
Gets the list of children of this Parent as a read-only list.
如果你存储父容器的引用总是更好更安全,但理论上你可以通过(向下)转换 getParent()
方法返回的 Parent
对象到类型父容器的。
例如,如果将 ToolBar
添加到 VBox
:
((VBox) toolBar.getParent()).getChildren().remove(toolBar);
或者,如果你想更通用一点,你可以在类型检查后将返回的父对象转换为 Pane
,因为这个 class 是超级 class允许修改子列表的 JavaFX 容器数:
if (toolBar.getParent() instanceof Pane)
((Pane) toolBar.getParent()).getChildren().remove(toolBar);
不过,我建议存储父容器的引用,而不是遵循这些(或类似)方法之一,因为这不是一个干净的方法,并且由于向下转换不是一个安全的解决方案(没有类型检查) .
我可以在不知道父级的情况下从场景图中删除 Node
吗?
换句话说,我可以做这样的事情吗?
@FXML private ToolBar toolBar;
@FXML
protected void handleCloseButtonAction(ActionEvent actionEvent) {
toolBar.getParent().getChildrenUnmodifiable().remove(toolBar);
actionEvent.consume();
}
如果我这样做,它会抛出 java.lang.UnsupportedOperationException
.
您得到 UnsupportedOperationException, because Parent#getChildrenUnmodifiable
returns 一个只读列表:
Gets the list of children of this Parent as a read-only list.
如果你存储父容器的引用总是更好更安全,但理论上你可以通过(向下)转换 getParent()
方法返回的 Parent
对象到类型父容器的。
例如,如果将 ToolBar
添加到 VBox
:
((VBox) toolBar.getParent()).getChildren().remove(toolBar);
或者,如果你想更通用一点,你可以在类型检查后将返回的父对象转换为 Pane
,因为这个 class 是超级 class允许修改子列表的 JavaFX 容器数:
if (toolBar.getParent() instanceof Pane)
((Pane) toolBar.getParent()).getChildren().remove(toolBar);
不过,我建议存储父容器的引用,而不是遵循这些(或类似)方法之一,因为这不是一个干净的方法,并且由于向下转换不是一个安全的解决方案(没有类型检查) .