Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple key press on JavaFX scene

Tags:

java

javafx

How are multiple key events detected in a single scene? I need my program to detect when the space bar and the right arrow keys are pressed simultaneously.

scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
    public void handle(KeyEvent ke) {
        if (ke.getCode() == KeyCode.RIGHT) {
            ///
        }

        if (ke.getCode() == KeyCode.LEFT) {
            ///
        }

        if (ke.getCode() == KeyCode.SPACE) {
            ///
        }

        if (ke.getCode() == KeyCode.RIGHT && ke.getCode() == KeyCode.SPACE) {
            // How??
        }
    }
});

The first 3 expressions look for a single key and work fine. The final expression never returns true. I believe only the latest key event is passed to the handler.

I looked at KeyCodeCombination, however this appears to be for use in cases when a key has a modifier key from a specified list (ALT_DOWN, SHIFT_DOWN, etc).

Is there a utility in FX that I can use?

like image 399
burntsugar Avatar asked Apr 14 '14 05:04

burntsugar


1 Answers

Try this:

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);
        }
    }
});
like image 124
James_D Avatar answered Sep 30 '22 20:09

James_D