2017-07-15 136 views
1

那么,如何结束一个按钮上的应用程序/游戏点击并退出,就好像窗口红色关闭符号(X)已被点击或更好的一样 如何结束当前的应用程序,而不关闭整个窗口/舞台开始一个新的? 因此,例如,我们有一些像结束应用程序(游戏)并退出或开始新的应用程序

public class Main extends Application 
{ 
    public Scene scene ; 
    private parent createContent() 
    { 
     // root pane, nodes and everything is here 
     //which makes up the game 
     //return root; 
    } 

    @Override 
    public void start(Stage stage) 
    { 
    scene = new Scene(createContent()); 
    stage.setScene(scene); 
    stage.show(); 
} 

public static void main(String[] args) {launch(args); } 
} 

因此,在目前的游戏结束时,用户应给予开始新游戏或通过点击按钮完全退出应用程序的选项。如果他应该点击退出游戏,那么游戏应该关闭,就好像他已经按下窗口红色x关闭符号一样。 如果用户应该点击开始一个新的游戏,那么优先行为将用于私人父母createContent() 方法 重新开始,但当然所有阶段和节点在以前的createContent()调用中创建应该被淘汰..

这怎么办?

+0

'Platform.exit()'退出(src:https://docs.oracle.com/javafx/2/api/javafx/application/Application.html) – frozen

+0

好的,谢谢...现在任何帮助启动没有关闭应用程序的新游戏? – Micky

回答

0

我在我的项目中有类似的工作流程,我实现了下一步。 enter image description here

注册一个处理器OnCloseRequest:

stage.setOnCloseRequest(windowEvent -> appToBeClosed(stage, windowEvent)); 

下面的方法来显示一个问题的对话。只有当一个用户决定留下来,你应该消耗当前窗口事件,并做一些事情,否则该应用程序将被关闭:

private void appToBeClosed(Stage notUsedStage, WindowEvent windowEvent) { 
    if (hasNotSavedEvents()) { 
     final Optional<ButtonType> userResponse = alertAboutNotSavedChangedEvents(
       "alert.changed.header", "alert.changed.content"); 
     if (userResponse.isPresent() && userResponse.get() == ButtonType.NO) { 
      windowEvent.consume(); 
     } 
    } 
} 

private Optional<ButtonType> alertAboutNotSavedChangedEvents(String headerResourceKey, 
                  String contentResourceKey) { 
    final Alert alert = new Alert(); 
    // TODO prepare alert as you wish... 

    return alert.showAndWait(); 
} 

我希望主要思想是明确的,你就可以把它采用到您的项目。 让我知道你的问题。