/ java

FXRoot Construct in JavaFX - HowTo

In this small tutorial I'll show you how to implement an FXRoot (fx:root) construct in JavaFX and with this you can use an JavaFX scene like an Vbox or AnchorPane as the Controller.

Extend your Pane
public class FXRootExampleAnchorPane extends AnchorPane implements Initializable

First extend your custom AnchorPane and implement Initalizeable because we'll have to wait for the @FXML items to load.

Load the FXML
    public FXRootExampleAnchorPane() {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass()

        try {
        } catch (IOException e) {

In our constructor we create an new FXMLLoader and give him our FXML.

Our FXML looks like this:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>

<fx:root maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" type="AnchorPane" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1">
      <Label layoutX="213.0" layoutY="192.0" text="FXRoot Construct Example" />
      <Button fx:id="someButtonBtn" layoutX="483.0" layoutY="360.0" mnemonicParsing="false" text="Some Button" />

The important thing is to define an fx:root with the type="AnchorPane then you can load the fxml into your controller.

In our initalize() method we initalize our someButtonBtn with an EventHandler.

Sometimes we need this construct to pass some references to our view.

If you have questions - comment below :)