Search code examples
model-view-controllerjavafxsingleton

Is a singleton controller possible in JavaFX(ML)?


I tried to implement a controller with the singleton pattern like described a couple of times on the web.

However I cant get the application to run because of the following exception.

java.lang.IllegalAccessException: Class sun.reflect.misc.ReflectUtil can not access a member of class testapp.Controller with modifiers "private"

I guess thats because the constructor is declared private. I dont see what I am doing wrong at this point.

In case I wasn't clear what my problem is I will describe the use case of what I am going to do.

Inside the start(Stage stage) function afaik is the only place the onclose event can be defined(please correct me if I am wrong). On closing the window some clean-up operations need to be exectued. These operation are inside the controller which I cant get access of in the start() function. Therefore the idea was to build the controller as a singleton to keep one single instance alive and provide acces to the main class.

The Link Creating a Singleton Controller class in JavaFX advised by sillyfly seems not to be a possible sollution for me bacause the controller is passed to a model class not the main class. Also the model constructor is called manually which is not the case I am dealing with.


Solution

  • To solve your problem you have two possibilities. Either you provide an instance of your singleton controller to the FXML loader which you have instantiated yourself https://docs.oracle.com/javase/8/javafx/api/javafx/fxml/FXMLLoader.html#setController-java.lang.Object- or you provide the FXML loader with a controller factory which knows how to instantiate your controller. https://docs.oracle.com/javase/8/javafx/api/javafx/fxml/FXMLLoader.html#setControllerFactory-javafx.util.Callback-