Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFx close window on pressing esc?

Tags:

javafx

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();
            }
        }
    });
like image 330
Chromos Avatar asked Jan 16 '13 11:01

Chromos


1 Answers

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();
          }
        }
    });
like image 77
Anshul Parashar Avatar answered Sep 24 '22 15:09

Anshul Parashar