2

Is it possible to create a constructor inside of a Javafx controller class?

My code was running well, and only gave me a runtime error when I created a constructor inside one of the controller classes

Ressay
  • 69
  • 9
  • 2
    Are you sure it's a _compilation_ error and not a _runtime_ error (e.g. `NoSuchMethodException`)? That said, by default the `FXMLLoader` requires the controller class to have a no-argument constructor, but you can customize the process by [setting a controller factory](https://openjfx.io/javadoc/13/javafx.fxml/javafx/fxml/FXMLLoader.html#setControllerFactory(javafx.util.Callback)). The controller factory would be responsible for invoking the appropriate constructor with the appropriate arguments. – Slaw Jan 02 '20 at 20:28
  • @Slaw yes you are right, it is a runtime error because it mentioned something related to method invoking. – Ressay Jan 02 '20 at 20:43
  • 1
    The other option is to remove `fx:controller` from your FXML file, manually instantiate the controller class, then call `FXMLLoader#setController(Object)` before calling `#load()`. And note that whatever approach you choose, the constructor will be invoked before any `@FXML` fields are injected. – Slaw Jan 02 '20 at 20:44
  • 1
    You could use a [custom control](https://docs.oracle.com/javase/8/javafx/fxml-tutorial/custom_control.htm). It's similar to the [`setController`](https://openjfx.io/javadoc/12/javafx.fxml/javafx/fxml/FXMLLoader.html#setController(java.lang.Object)) method but also adds [`setRoot`](https://openjfx.io/javadoc/12/javafx.fxml/javafx/fxml/FXMLLoader.html#setRoot(java.lang.Object)). If you do of all the fxml work (setting the root, setting the controller, loading the fxml) in the constructor for the custom control, you should be able to have a constructor with parameters for your custom control. – jewelsea Jan 02 '20 at 21:17
  • 1
    As said in previous comments you can just do this `loader.setController(new Controller())` (`loader` is `FXMLLoader` object). This will call the constructor of the loader. But it is better to use an `Initializable` more information [here](https://stackoverflow.com/questions/34785417/javafx-fxml-controller-constructor-vs-initialize-method) – fuggerjaki61 Jan 03 '20 at 13:19

0 Answers0