使用JavaFX进入和退出应用程序

时间:2017-04-05 03:16:22

标签: java javafx javafx-8

我对JavaFX有一些看起来很像bug的奇怪问题。我想做以下事情:

  • 启动我的应用程序时输入fullscren
  • 按escape退出应用程序(不是全屏,整个应用程序)

到目前为止,我有以下代码:

public class AppTest extends Application {

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

  public void start(Stage stage) {
    stage.setOnCloseRequest(t -> {
      Platform.exit();
      System.exit(0);
    });

    stage.setFullScreenExitHint("Press ESCAPE to exit");
    stage.setFullScreenExitKeyCombination(KeyCombination.NO_MATCH);
    stage.setFullScreen(true);

    Rectangle2D screenBounds = Screen.getPrimary().getBounds();
    stage.setX(screenBounds.getMinX());
    stage.setY(screenBounds.getMinY());

    double screenWidth = screenBounds.getWidth();
    double screenHeight = screenBounds.getHeight();

    stage.setWidth(screenWidth);
    stage.setHeight(screenHeight);

    Group root = new Group();
    Scene scene = new Scene(root);
    stage.setScene(scene);

    scene.setOnKeyTyped(event -> {
      if(event.getCode() == KeyCode.ESCAPE) {
        stage.close();
      }
    });

    Canvas canvas = new Canvas(screenWidth, screenHeight);
    root.getChildren().add(canvas);

    GraphicsContext gc = canvas.getGraphicsContext2D();

    gc.setFill(Color.BLUE);
    gc.fillRect(0,0, screenWidth, screenHeight);

    stage.show();
  }

}

我在macOS上。

一般情况下,全屏显示。我总的说是因为这段代码的真实版本并不总是如此。有时,它只是一个最大化的窗口。

然后,当按下escape时,我得到一个最大化窗口而不是退出应用程序。

我该如何解决?

1 个答案:

答案 0 :(得分:2)

变化:

scene.setOnKeyTyped

要:

scene.setOnKeyReleased

This解释了原因。

相关问题