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?
Asked
Active
Viewed 3,962 times
6
-
3How about using a BorderPane.The button will be at the bottom and you change only the center with your fxml files. – GOXR3PLUS Sep 02 '16 at 22:14
-
Simple and effective! Thank you I didn't think about this. – Loïs Talagrand Sep 03 '16 at 00:57
2 Answers
10
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.

kerner1000
- 3,382
- 1
- 37
- 57
0
This can definitely be achieved by creating a separate FXML file and add a Node to it with a known unique Id, then accessing that node via the id, the tricky part is how are you going to do it application wide? probably creating the same function in a lot of your controllers but here is how you would get a a button from an FXML file.
All buttons are performing the same action?
Parent root = FXMLLoader.load(getClass().getResource("fileName.fxml"));
ObservableList<Node> nodes = root.getChildrenUnmodifiable();
String _id = "testButton";
for (Node node : nodes) {
if (node.getId().equals(_id)) {
return node;
}
}
return null;
}

Sam Orozco
- 1,258
- 1
- 13
- 27