Rocky
Rocky

Reputation: 431

How to change parent of child fxml into other parent?

Can I change a Node's parent to another parent in FXML?

Suppose a parent named stackcon with a child node. I now want to move this child node to different parent, e.g., named stackmain.

Is this possible? If yes, please give me a link or a example code.

Upvotes: 0

Views: 2939

Answers (2)

Ali Faris
Ali Faris

Reputation: 18592

it may vary depending on type of the pane of stackmain & stackcon , i'm assuming that you use AnchorPane

but it is something like this

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

Upvotes: 1

Markus Weninger
Markus Weninger

Reputation: 12648

This is just one of many ways how to do this.

MainView.fxml, just a simple view containing a button, and on button click the label should be moved from right to left and vice-versa (see the onMousePressed declaration):

<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>

The controller MainView.java with its switchButtonPressed event handler:

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);
        }
    }
}

You see, I just check on button click if the label is on the left side. If so, remove it on the left side and add it on the right side. Analogous, if it is on the right side, remove it there and add it on the left side.

Upvotes: 1

Related Questions