我在程序中调用了一个新阶段,我想在按Escape键时关闭该阶段。我这样做是给我一个NullPointerException:

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

最佳答案

尝试这个..

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

关于javafx - JavaFx在按esc时关闭窗口?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14357515/

10-12 22:30