2

I have strange problems with JavaFX that look a lot like a bug. I want to do the following:

  • Entering fullscren when starting my application
  • Press escape to exit the application (not fullscreen, the entire application)

So far, I have the following code:

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();
  }

}

I'm on macOS.

In general it goes fullscreen. I'm saying in general because the real version of this code doesn't always. Sometimes, it is just a maximized window.

Then, when pressing escape, I get a maximized window instead of exiting the application.

How can I fix that?

Henri
  • 5,551
  • 1
  • 22
  • 29

1 Answers1

2

Change:

scene.setOnKeyTyped

To:

scene.setOnKeyReleased

This explains why.

Community
  • 1
  • 1
SedJ601
  • 12,173
  • 3
  • 41
  • 59
  • I was so close :-) And to others, I will confirm that the `NO_MATCH` is required. Otherwise, it won't exit the application. – Henri Apr 07 '17 at 15:39