JavaFX程序第二次调用Stage.show()时自动终止问题求助
JavaFX关闭后重新打开舞台导致程序终止的原因与解决方法
问题原因
JavaFX默认的舞台关闭操作是EXIT_ON_CLOSE——当最后一个可见的舞台被关闭时,系统会自动执行Platform.exit()终止整个应用程序。
你的代码中,第一次关闭窗口时,虽然通过setOnHidden回调触发了showBuild()尝试重新显示舞台,但此时EXIT_ON_CLOSE的退出逻辑已经启动,应用进入终止流程。因此第二次调用stage.show()时,舞台会短暂显示后随应用终止而关闭,最终程序以退出码0正常结束。
解决方法
将舞台的关闭操作改为HIDE_ON_CLOSE,这样关闭窗口时仅隐藏舞台,不会触发应用退出逻辑,后续就能正常调用stage.show()重新打开窗口。
修改后的代码
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; import javafx.stage.Stage.CloseOperation; public class Example extends Application{ static BorderPane mainPane = new BorderPane(); static Scene scene; static Stage stage; public static void main(String[] args) { launch(args); } public void start(Stage newStage) { stage = newStage; // 设置关闭操作仅隐藏窗口,不退出应用 stage.setCloseOperation(CloseOperation.HIDE_ON_CLOSE); scene = new Scene(mainPane, 640, 700); stage.setScene(scene); stage.setOnHidden(e -> showBuild()); showBuild(); } public static void showBuild() { stage.show(); } }
内容的提问来源于stack exchange,提问作者Untitled
相关产品推荐
相关产品推荐

