问题
I have a small game which has New Game button. There are many variables which need reset when the New Game button is pressed. Is there any method which can easily reload the whole application or any alternative to refresh the scene, stage or variables? I just want to bring the application to it's initial stage when It's first loaded.
I went through different topics on internet and read many questions and answers here also, but I there is no easy method to implement it. Most of the answers suggest to reuse the whole code or put the whole code in class and reload it.
Questions reviewed:
- How to restart a JavaFX application when button is clicked?
- How can you reload or refresh a scene with javafx 1.3
回答1:
I would certainly recommend a clean approach as discussed in the questions you linked.
A quick and dirty way however might be the following:
restartButton.setOnAction( __ ->
{
System.out.println( "Restarting app!" );
primaryStage.close();
Platform.runLater( () -> new ReloadApp().start( new Stage() ) );
} );
Close the main stage, create a new one and pass it to a new instance of your App. I cannot make any guarantees about the memory behavior of this hack. Use it carefully.
Full example: https://gist.github.com/bugabinga/ce9e0ae2328ba34133bd
回答2:
for reload application you must create new instance of your main class and call the start method of it with stage parameter.for example
restartButton.setOnAction(e->{yourAPP app=new yourApp();
app.start(yourStage);});
来源:https://stackoverflow.com/questions/35858903/how-to-reload-an-application-in-javafx