Reading:
JavaFX Load FXML into another FXML

JavaFX Load FXML into another FXML

Metamug
JavaFX Load FXML into another FXML

In JavaFX, you can load one FXML file into another by using the <fx:include> tag. This tag allows you to include an external FXML file as a child of another FXML file.

Here's an example of how to load an FXML file called Child.fxml into another FXML file called Parent.fxml.

Create Child.fxml and Parent.fxml files in your project directory.

In Child.fxml, define the layout and content you want to include in the parent FXML file:

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.VBox?>

<VBox xmlns="http://javafx.com/javafx"
      xmlns:fx="http://javafx.com/fxml"
      fx:controller="com.example.ChildController">
    <!-- Add content to the child FXML file here -->
</VBox>

In Parent.fxml, add the tag to include the child FXML file:

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.VBox?>

<VBox xmlns="http://javafx.com/javafx"
      xmlns:fx="http://javafx.com/fxml"
      fx:controller="com.example.ParentController">

    <!-- Add other content to the parent FXML file here -->

    <fx:include source="Child.fxml"/>

    <!-- Add other content to the parent FXML file here -->

</VBox>

In the ParentController class, you can access the included child FXML file and its controller by calling getController() on the FXMLLoader:

public class ParentController {

    @FXML
    private VBox childContainer;

    @FXML
    private void initialize() {
        try {
            FXMLLoader childLoader = new FXMLLoader(getClass().getResource("Child.fxml"));
            VBox childNode = childLoader.load();
            ChildController childController = childLoader.getController();
            // Do something with the child node and controller
            childContainer.getChildren().add(childNode);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Note that you need to call load() on the FXMLLoader object to load the child FXML file and its controller. Once you have loaded the child FXML file, you can access its controller by calling getController(). In this example, we add the child node to a VBox container in the parent FXML file.



Icon For Arrow-up
Comments

Post a comment