结束应用程序(游戏)并退出或开始新的应用程序

时间:2017-07-15 22:07:32

标签: javafx-8

那么如何在点击按钮上结束应用程序/游戏并退出,就好像已经点击了窗口红色关闭符号(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()中创建的所有阶段和节点。

如何做到这一点?

1 个答案:

答案 0 :(得分: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();
}

我希望主要想法很明确,您将能够将其应用到您的项目中。 让我知道你的问题。

相关问题