JavaFX – Many Static FXML Controllers

A JavaFX application exists and the application is starting from the Main.class file which extends Application:

  public class Main extends Application {

    /**
     * Keep a reference to the main Stage
     */
    public static Stage                 stage;
    /**
     * MainScene Controller
     */
    public static MainScene             mainSceneController;
    /**
     * The Capture Window of the application
     */
    public static CaptureWindow         captureWindowController;
    /**
     * Settings Scene Controller
     */
    public static SettingsController    settingsController;

    @Override
    public void start(Stage primary) throws Exception {

        stage = primary;
        ..........

        // CaptureWindow
        FXMLLoader loader1 = new FXMLLoader(getClass().getResource("/fxml/CaptureWindow.fxml"));
        loader1.load();
        captureWindowController = loader1.getController();

        // MainScene
        mainSceneController = new MainScene();

        .........   
    }

  }

Description

As you can see above I have 3 FXMLControllers(one is reusable[extends StackPane],others not).I have declared all of them static cause i want to access variables from one FXMLController from the other FXMLControllers.I use this strategy every time I use JavaFX and I don’t think is good…

How I can change the code below so I can access variables or methods of one FXMLController from other FXMLController? Is that possible without using static keyword?

Consider that the Controllers are represented from different classes which can be in different packages.


Also before writing this question I had a look Static @FXML variables in FXML Controller

Answer

Actually the answer for this question seems a little bit complicated it has to do with MVC pattern and it’s evolution until now.We will use MVP Pattern.

After a long discussion i got a link on this website http://martinfowler.com/eaaDev/uiArchs.html defining the historical evolution of the different patterns used from the old ages of Smalltalk until now.


The actually solution is using Model Viewer Presenter Pattern(MVP) which can be visually described using these images:

enter image description here

enter image description here

For more you can read(http://www.wildcrest.com/Potel/Portfolio/mvp.pdf)


For an example on JavaFX have a look on James_D answer here (Applying MVC With JavaFx)


Last but not least have a look at the comments here:

Finally:

If anything is inaccurate feel free to edit.

Leave a Reply

Your email address will not be published. Required fields are marked *