fx:controller="" in .FXML


Question

is it possible to add two controllers (fx:controller="") in one FXML file ?

I could managed to add only one as fx:controller=""

See the 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">
1
4
3/22/2013 8:03:42 AM

Accepted Answer

You can't set more than one controller within an FXML file using (fx:controller=""), instead consider injecting the controller manually, basically there are two ways :

Using setController method without mention 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();

More appropriately, use setControllerFactory method :

first, make sure that both of the controllers ClientArea and Undecorator implement an interface (Icontroller, containing the event Handler methods) mentioned in the FXML file (fx:controller="IController"), then choose 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
4/15/2013 3:10:46 PM

If fits in your code, your Undecorator.java could extend from ClientArea.java. So, any method (or FXML method/control) could be used from its parent: ClientArea.java. Using JavaFX SceneBuilder, won't show you the package.ClientArea in the controller selection, but at runtime it will work.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon