Javafx Initialize Controller Constructor only Once?

Viewed 559

I'm building a Javafx gui application and I'm facing this problem. I do have multiple Scenes for my program and so i have different FXML files and Controller classes. The thing is that in the first "Main Menu" (which is the first that pops up in my app) scene, in the Constructor of the Controller i call some heavy methods loading data from database and more. So what happens it this. In the next scenes i do have "Main Menu Buttons", that switch to Main Menu scene! So every time i go back to the "Main Menu" scene the constructor call the heavy methods loading data. Whereas i don't want that. I don't want to call these methods every time, just Once at the start. Here is some example code simplified :

Main Menu Scene(Controller)

public class MainController {

    @FXML
    Button bt1 = new Button();
    @FXML
    Button bt2 = new Button();
    @FXML
    Button bt3 = new Button();
    public static int choice=0;

    //constructor
    public MainController(){
        try {
           //heavy databse tasks here(loading data)
        }catch (Exception e){
            //error handling
        }


    }

    @FXML
    public void initialize(){}
}

Another Controller class

public class Scene2Controller {

    private Button mainMenu = new Button();

    //constructor
    public Scene2Controller(){}

    @FXML
    public void initialize(){}

    public void goMainMenu(ActionEvent actionEvent) throws IOException {
        Parent menu= FXMLLoader.load(getClass().getResource("/mainScene.fxml"));
        Stage window = (Stage) mainMenu.getScene().getWindow();
        window.getScene().setRoot(menu);
        window.show();
    }
}

So in the Second controller i have a listener method that when buttons clicks it goes back to the main menu scene, loading the appropriate FXML file.

I understand that this seams pretty straight forward to most of you, but im new in javafx and i wanted to know if i there is something doing wrong switching scenes or that i should do different in order for these methods that i have in the mainMenu Constructor class, to run Only Once. Is that obtainable or should i create a Sub-Controller class that run before the Main Menu Scene? Thanks in advance.

1 Answers

In my case i had to call few methods, so i just removed them from the first Scene Controller class and add them in the start() method in my MainClass and not inside a Controller class. I think @James_D 's response is the overall best for a similar question like mine one. Thanks !

Related