How to check if a key is down without a listener in JavaFX?

Viewed 463

Is it possible to simply check if a key is currently pressed in JavaFX without listening for a KeyEvent? In my case I want to check if a key is down while a button is being pressed.

button.setOnAction(e -> {
    // This is where I want to check if a specific key is currently down.
    if(keyIsDown) {
        // do something
    } else {
        // do something else
    }
});

I can think of a couple of workarounds. I'm just wondering if there is a right way to do this.

1 Answers

Here you go this code works like a charm with me when I'm pressing any button on keyboard then click a button prints key down

    SimpleBooleanProperty simpleBooleanProperty = new SimpleBooleanProperty();

    scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent event) {
            simpleBooleanProperty.setValue(true);
        }
    });

    scene.setOnKeyReleased(new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent event) {
            simpleBooleanProperty.setValue(false);
        }
    });


    done.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            if(simpleBooleanProperty.get()){
                System.out.println("Key Down");
            }else { //key released
                System.out.println("Key Up");
            }
        }
    });
Related