Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX - Reusable FXML component

I am building a GUI with Scene Builder, and the majority of my scenes have one element in common (an iOS type home button at the bottom). I was wondering if it was possible to define this component in a separate fxml file. From the research I conducted, there exists a similar process for declaring a reusable component but only within the same fxml file. How could I apply this principle for several fxml files?

like image 820
Loïs Talagrand Avatar asked Feb 07 '23 05:02

Loïs Talagrand


1 Answers

You can do like this:

<AnchorPane xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.example.MainController">
<children>
<fx:include fx:id="someId" source="NestedFXML.fxml"/>
</children>
<AnchorPane xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.example.NestedFXMLController">
</AnchorPane>

Controller classes:

public class MainController implements Initializable {

    @FXML
    private NestedFXMLController someIdController;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
    // TODO Auto-generated method stub

    }
}

and

public class NestedFXMLController implements Initializable {

    @Override
    public void initialize(URL location, ResourceBundle resources) {
    // TODO Auto-generated method stub

    }
}

Note that the nested controller can be injected via FXML annotation. The field name must match the fx:id attribute string + "Controller"!

Find a MWE here.

like image 167
kerner1000 Avatar answered Feb 17 '23 02:02

kerner1000