How to restart a JavaFX application when a button is clicked

后端 未结 1 599
星月不相逢
星月不相逢 2020-12-31 12:56

I went through almost every post here regarding the matter but most of them doesn\'t explain what to do properly. To the question:

I created a javaFX application, a

1条回答
  •  别那么骄傲
    2020-12-31 13:35

    You already noticed that you cannot do the launching process again. Therefore your best option is to rewrite the application class and move the initialisation logic to a new method:

    void cleanup() {
        // stop animations reset model ect.
    }
    
    void startGame(Stage stage) {
        // initialisation from start method goes here
    
        btnNewGame.setOnAction(e -> {
           restart(stage);
        });
    
        stage.show();
    }
    
    void restart(Stage stage) {
        cleanup();
        startGame(stage);
    }
    
    @Override
    public void start(Stage primaryStage) {
        startGame(primaryStage);
    }
    

    Notes

    • Depending on the parts of the scene changed, it may be enough to change the state of some of the nodes (more efficient than creating a new scene). (Just take a look at the changes you made during the game and decide for yourself)
    • launch() is a static method and you should not create a instance of your application class yourself for that reason. Use Application.launch(GameUI.class, args); instead and let the method handle the creation of the GameUI instance.
    • It may be a better design to move the UI creation to a class different to the application class. This way reuse of the code is easier, since it does not require the creation of a instance of a subclass of Application.

    0 讨论(0)
提交回复
热议问题