java 如何在 JavaFX 中重新加载应用程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35858903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to reload an Application in JavaFX?
提问by Maihan Nijat
I have a small game which has New Gamebutton. There are many variables which need reset when the New Gamebutton 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:
回顾的问题:
回答by Oliver Jan Krylow
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.
关闭主阶段,创建一个新阶段并将其传递给您的应用程序的新实例。我不能对这个 hack 的内存行为做出任何保证。小心使用。
Full example: https://gist.github.com/bugabinga/ce9e0ae2328ba34133bd
完整示例:https: //gist.github.com/bugabinga/ce9e0ae2328ba34133bd
回答by user3235815
for reload application you must create new instance of your main class and call the start method of it with stage parameter.for example
对于重新加载应用程序,您必须创建主类的新实例并使用 stage 参数调用它的 start 方法。例如
restartButton.setOnAction(e->{yourAPP app=new yourApp();
app.start(yourStage);});