Hello! How to trace pressing more than one key at a time in JavaFX?

    2 answers 2

    try it

    final BooleanProperty spacePressed = new SimpleBooleanProperty(false); final BooleanProperty rightPressed = new SimpleBooleanProperty(false); final BooleanBinding spaceAndRightPressed = spacePressed.and(rightPressed); // How to respond to both keys pressed together: spaceAndRightPressed.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<Boolean> obs, Boolean werePressed, Boolean arePressed) { System.out.println("Space and right pressed together"); } }); // Wire up properties to key events: scene.setOnKeyPressed(new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent ke) { if (ke.getCode() == KeyCode.SPACE) { spacePressed.set(true); } else if (ke.getCode() == KeyCode.RIGHT) { rightPressed.set(true); } } }); scene.setOnKeyReleased(new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent ke) { if (ke.getCode() == KeyCode.SPACE) { spacePressed.set(false); } else if (ke.getCode() == KeyCode.RIGHT) { rightPressed.set(false); } } }); 
    • Yes, it works with some fixes. Thank you very much! - Romeon0
    • @ Romeon0 glad I could help. you can write what you did or accept my answer as correct - Senior Pomidor

    I will add from myself:

    In the javafx.scene.input package there is an easy-to-use class KeyCodeCombination whose constructor accepts a keystroke and modifier as an attribute. In this class, the match method (KeyEvent e) is implemented.

    Example of use:

     public void start(Stage primaryStage) throws Exception { Label l = new Label(); Pane p = new Pane(l); Scene s = new Scene(p, 200, 200); KeyCodeCombination kComb = new KeyCodeCombination(KeyCode.A, KeyCombination.ALT_ANY); s.setOnKeyPressed(e -> { if (kComb.match(e)) l.setText("Hello"); }); primaryStage.setScene(s); primaryStage.show(); }