Search code examples
javajavafxwindow

JavaFX - opening multiple windows on application startup


There are a couple questions on how to open a new window on pressing a button, but I'd like to open two windows when the application is launched.

My current approach is to put the following code in a new class that functions as the controller of the new window:

FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("secondWindow.fxml"));
        fxmlLoader.setController(this);
        try {
            parent = (Parent) fxmlLoader.load();
            scene = new Scene(parent, 500, 400);
            stage = new Stage(scene);
            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
        }

This works great for buttons or event based openings of windows, I am looking for a simultaneous launching of the two windows. Therefore I'd like to launch my second window from the class with the main method.

In this class you can find the first window being launched using this code:

Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();

Right below I'd like to add code to launch the second window. I tried:

Parent secondRoot = FXMLLoader.load(getClass().getResource("secondWindow.fxml"));
        Scene secondScene = new Scene(secondRoot);
        Stage secondStage = new Stage();
        secondStage.setScene(secondScene);
        secondStage.show();

which to my understanding should do it, but it gives the following error:

java.lang.NoSuchMethodException: monopolybank.SecondWindowController.<init>()
    at java.lang.Class.getConstructor0(Class.java:2971)
    at java.lang.Class.newInstance(Class.java:403) 

How can I fix my approach or what are alternatives to get the same result?


Solution

  • Your problem is nothing to do with the number of windows and all to do with a constructor with parameters that you added to the monopolybank.SecondWindowController class that you created => remove the constructor from that class.