Is a singleton controller possible in JavaFX(ML)?

singleton java
singleton pattern javafx
javafx application singleton
singleton class

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.

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-

Communication between Controller and Main class in JavaFX , Of course, it would be possible to make the Stage and the Scene static in the Main.java but it kinda is hard to Is a singleton controller possible in JavaFX(ML )?. The problem is that in JavaFX you can hardly manage the instantiation of the controllers. By default, the controller of a view is automatically instantiated (using its free-parameter constructor) during the loading of the view (in the case the FXML attribute controller is specified).

This just reads like an X-Y problem to me.

It makes no sense (to me) to make a controller a singleton. In practice, every JavaFX controller is stateful and needs some access to the view state: at some point you are going to want to check the text that is in a text field, or the selected item in a combo box, etc, so you need to have references to the elements of the view (the text field or combo box, etc). Because of this, in practice, you need to have a 1-1 correspondence between controller instances and instances of the hierarchy defined by the FXML file. So if you make the controller a singleton, then you can only ever load the FXML file once.

The problem is that there is no way to enforce (at the same level of enforcement as a singleton works) "only load this FXML file once". Thus you have to enforce this rule solely by your programming logic. Of course, once you do this, your programming logic now enforces that you only have one controller instance anyway, so you effectively achieve the same thing. If you enforce this by programming logic, it allows you to reuse the controller-FXML view pair if you later want to; making the controller class a singleton prevents it, though it will not be apparent from your application code that this is the case. So making the controller a singleton reduces reuse (in a way that will not be obvious when you return to the code) while providing no additional benefit.

Your state in your question that you "need" to do this because you need to access the controller in the onClose handler for the primary stage. I don't see why you can't just access the controller in the usual way:

@Override
public void start(Stage primaryStage) throws IOException {

    FXMLLoader loader = new FXMLLoader(getClass().getResource("/path/to/fxml/file.fxml"));
    Parent root = loader.load();
    Scene scene = new Scene(root);
    primaryStage.setScene(scene);

    MyControllerClass controller = loader.getController();
    primaryStage.setOnHidden(e -> {
        // do clean-up:
        controller.shutdown();

        // ...
    });

    primaryStage.show();
}

Even if you delegate loading the FXML to some other class, you must have some route defined between the start method (with its reference to the primary stage) and the method that loads the FXML, so you have a route through which you can pass the stage reference or pass the controller reference to achieve what you need.

JavaFX Tips and Tricks: Using Singleton Pattern , Features of JavaFX such as declarative UI scripting, and binding, make it very natural to use a model-view-controller pattern. I typically have at� The JavaFX Controller. The remaining piece of the puzzle for the ‘About’ dialogue is the controller itself, AboutController. The FXML file about.fxml has a reference to the controller class to enable JavaFX to know which class to instantiate and where to inject the close button and the other GUI components:

In other class:

@FXML
private void btnIngresarOnAction() {
    try {
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(getClass().getResource("/fxml/Frame.fxml"));
        Parent rootNode = fxmlLoader.load();
        Stage stage = new Stage();
        stage.setTitle("Frame");
        Scene scene = new Scene(rootNode);
        stage.setOnCloseRequest(event -> FrameController.frame = null);
        stage.setScene(scene);
        stage.show();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

In class singleton:

@Lazy
@Component
public class FrameController implements Initializable {

    public static FrameController frame;

    public FrameController() {
        if (frame == null) {
            frame = this;
        } else {
            throw new RuntimeException("Singleton FXML");
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        System.out.println("Initialize");
    }
}

How to make a JavaFX controller class of an FXML file singleton , a single instance of some UI to exist, making the controller a singleton to where and how to start handling JavaFX (thank you in advance)?. Here we will learn about Singleton design pattern principles, different ways to implement the Singleton design pattern and some of the best practices for its usage. Singleton Pattern Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.

Singleton by Raizlabs, about 4 years singleton object deallocated when app crashes Is a singleton controller possible in JavaFX(ML)?; ruby instance has no content� Is it possible to get a reference to the primary Stage in a running JavaFX application ?. The context of this question is that I would like to write a library that manipulates a JavaFX interface from another language (Prolog). In order to do this, my library requires access to the primary Stage.

Managing a multitude of scenes in a menu system (JavaFX forum at , I'm considering making each class a singleton extending an abstract It's also possible that I prevent anything except a ViewController from� I made a structure to of Controllers and Views (fxml) to separate my code as much as I could, and I'm wondering how to communicate between 2 controllers. I mean, a controller have to call some func

artisan command to add resources to controller Code Example, Get code examples like "artisan command to add resources to controller" instantly right Possible solutions: close all other connection(s); use the server mode� Before you start, ensure that the version of NetBeans IDE that you are using supports JavaFX 2.2. It is assumed that you are familiar with the basic structure of an FXML project (.java, .fxml, and controller files).

Comments
  • Possible duplicate of Creating a Singleton Controller class in JavaFX
  • I cant use this approach because i need the controller instance in the main class to use it in the onclose event. I cant just pass the controller backwards. (Or can I?)
  • I don't see any reason why you won't be able to. Please edit your question to better explain exactly what you need, and why the linked answer doesn't work for you.
  • I'm confused by "I can't access the controller from the start() method." Where are you loading the FXML? If you're using a singleton pattern solely to get convenient access to an object, then you have fundamentally misunderstood that pattern.
  • The first one is what I was trying to do. But it ends in a exception because the controller constructor is private and javafx cannot use class with a private constructor as a controller. I dont know whats behind your second idea. Could you show me an example or a existing thread which is dealing with that?
  • You did not understand what I said. I said controller instance not controller class.
  • Ofc! Thanks a lot. Nice and simple
  • Unless the controller is stateless, which seems highly unlikely, you end up with the possibility of two FXML structures sharing the same controller instance (and its state), which will almost certainly break. The problem is you need a 1-1 correspondence between instances of the FXML structure and controller instances, and there is no way to force the FXML structure to be a singleton. So while it's possible to do this, it never makes sense to do it.
  • That's another aspect of the original question but for practical purposes it is of course very important.