Fx: controller = "" in .FXML

Can I add two controllers ( fx:controller="" ) in one FXML file?

I managed to add only one of them: fx:controller=""

See code

 <BorderPane id="BorderPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="596.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml" fx:controller="demoapp.ClientArea"> 
+4
source share
2 answers

You cannot install more than one controller in an FXML file using (fx:controller="") , instead consider entering a controller manually, there are basically two ways:

Using the setController method without mentioning the controller inside the FXML file:

 FXMLLoader loader = new FXMLLoader(); URL location = getClass().getClassLoader().getResource("fxml/ClientArea.fxml"); loader.setLocation(location); loader.setController(new ClientArea()); // loader.setController(new Undecorator()); loader.load(); 

In a more appropriate way, use the setControllerFactory method:

first make sure that both ClientArea and Undecorator implement the interface ( Icontroller containing event handler methods) specified in the FXML file (fx:controller="IController") , then select the controller when loading your view from the FXML file:

 FXMLLoader loader= new FXMLLoader(); URL location = getClass().getClassLoader().getResource("fxml/ClientArea.fxml"); loader.setLocation(location); loader.setControllerFactory(new Callback<Class<?>, Object>() { public Object call(Class<?> p) { return new ClientArea(); // return new Undeorator(); } }); loader.load(); 
+2
source

If you fit into your code, your Undecorator.java may extend from ClientArea.java . Thus, any method (or FXML method / control) can be used from its parent: ClientArea.java . Using JavaFX SceneBuilder will not show you the .ClientArea package in choosing a controller, but it will work at runtime.

0
source

All Articles