Search code examples
javafx-2javafxfxml

fx:controller="" in .FXML


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">

Solution

  • 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 Undecorator();
        }
    });
    loader.load();