JavaFx close window on pressing esc?

2020-03-19 03:39发布

问题:

Im calling a new stage in my program which I like to close on pressing escape. I did this which gives me a NullPointerException:

    scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent t) {
            KeyCode key = t.getCode();
            if (key == KeyCode.ESCAPE){
                stage.close();
            }
        }
    });

回答1:

try this..

  scene.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>
  () {

        @Override
        public void handle(KeyEvent t) {
          if(t.getCode()==KeyCode.ESCAPE)
          {
              System.out.println("click on escape");
           Stage sb = (Stage)label.getScene().getWindow();//use any one object
           sb.close();
          }
        }
    });


回答2:

Add the event handler to the stage/window you want to close on ESC.

JavaFX 8 style:

    stage.addEventHandler(KeyEvent.KEY_RELEASED, (KeyEvent event) -> {
        if (KeyCode.ESCAPE == event.getCode()) {
            stage.close();
        }
    });


回答3:

why you dont show us more of your code? However, try this:

public class Login extends Application {

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

@Override
public void start(final Stage primaryStage) {
    primaryStage.setTitle("JavaFX Welcome");
    GridPane grid = new GridPane();
    grid.setAlignment(Pos.CENTER);
    grid.setHgap(10);
    grid.setVgap(10);
    grid.setPadding(new Insets(25, 25, 25, 25));

    Text scenetitle = new Text("Welcome");
    scenetitle.setId("welcome-text");
    grid.add(scenetitle, 0, 0, 2, 1);

    Label userName = new Label("User Name:");
    grid.add(userName, 0, 1);

    TextField userTextField = new TextField();
    grid.add(userTextField, 1, 1);

    Label pw = new Label("Password:");
    grid.add(pw, 0, 2);

    PasswordField pwBox = new PasswordField();
    grid.add(pwBox, 1, 2);

    Button btn = new Button("Sign in");
    HBox hbBtn = new HBox(10);
    hbBtn.setAlignment(Pos.BOTTOM_RIGHT);
    hbBtn.getChildren().add(btn);
    grid.add(hbBtn, 1, 4);

    Scene scene = new Scene(grid, 660, 300);
    scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
        public void handle(KeyEvent ke) {
            if (ke.getCode() == KeyCode.ESCAPE) {
                System.out.println("Key Pressed: " + ke.getCode());
                primaryStage.close();
            }
        }
    });
    //primaryStage.setFullScreen(true);
    primaryStage.setScene(scene);
    primaryStage.show();
}
}

Done.



回答4:

Hope the imported Eventhandler package is not of JavaFX.

Try using,

import javafx.event.EventHandler;

Note:As the naming convention are same but only the package name differs between swing and JavaFX, Your NetBeans/Eclipse may auto import different packages, so make sure of it.



标签: javafx