如何将子 fxml 的父级更改为其他父级?

How to change parent of child fxml into other parent?

我可以将 Node 的父级更改为 FXML 中的另一个父级吗?

假设一个名为 stackcon 的父节点有一个子节点。 我现在想将这个子节点移动到不同的父节点,例如,命名为 stackmain.

这可能吗?如果是,请给我一个link或示例代码。

这只是实现此目的的众多方法之一。

MainView.fxml,只是一个包含按钮的简单 view,单击按钮时标签应从右向左移动,反之亦然(请参阅 onMousePressed声明):

<fx:root type="BorderPane" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
    <left>
        <VBox fx:id="lefty">
            <Label fx:id="switchy" text="Switching text"></Label>
        </VBox>
    </left>
    <center>
        <Button fx:id="switchBtn" text="Switch" onMousePressed="#switchButtonPressed"></Button>
    </center>
    <right>
        <VBox fx:id="righty">
        </VBox>
    </right>
</fx:root>

控制器MainView.java及其switchButtonPressed事件处理程序:

public class MainView extends BorderPane {
    @FXML private VBox lefty;
    @FXML private VBox righty;
    @FXML private Label switchy;

    public MainView() {
        URL fxmlFile = MainView.class.getResource("MainView.fxml");
        FXMLLoader fxmlLoader = new FXMLLoader(fxmlFile);
        fxmlLoader.setRoot(this);
        fxmlLoader.setController(this);

        try {
            fxmlLoader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void switchButtonPressed(MouseEvent mouseEvent) {
        if(lefty.getChildren().contains(switchy)) {
            lefty.getChildren().remove(switchy);
            righty.getChildren().add(switchy);
        } else {
            righty.getChildren().remove(switchy);
            lefty.getChildren().add(switchy);
        }
    }
}

你看,如果标签在左侧,我只检查按钮点击。如果是这样,请将其从左侧删除并添加到右侧。 类似的,如果在右边,就把那里去掉,在左边加上。

它可能因 stackmainstackcon 窗格的类型而异,我假设您使用 AnchorPane

但它是这样的

Node childNode = stackcon.getChildren().get(indexOfChild);
stackcon.getChildren().remove(indexOfChild);
stackmain.getChildren().add(childNode);