/ 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()
                .getResource("/fxml/FXRootConstructExample.fxml"));
        fxmlLoader.setRoot(this);
        fxmlLoader.setController(this);

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

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">
   <children>
      <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" />
   </children>
</fx:root>

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