I have a program in javafx that is running and I want to call a function inside that program when a specific key is pressed on the keyboard (for example, the "a" key). I tried using an event handler on my scene but KEY_PRESSED seems to go off when any key is pressed, unless I am using it wrong. KEY_TYPED seems like it might suit my needs, but I've only found examples of that one in relation to text boxes, which is not what I'm looking for. Does anyone know how to do this, or have a good resource I can consult for something like this
By adding both key press and key release handlers and a boolean state for each key, you can keep track of whether you have processed the key since it was pressed. You can then reset that processed state whenever the key is released so that the next time it is really pressed you can handle it.
getCode() The key code associated with the key in this key pressed or key released event. EventType<KeyEvent> getEventType()
public class ActionEvent extends Event. An Event representing some type of action. This event type is widely used to represent a variety of things, such as when a Button has been fired, when a KeyFrame has finished, and other such usages.
Just check the code of the key that was pressed:
scene.setOnKeyPressed(e -> {
if (e.getCode() == KeyCode.A) {
System.out.println("A key was pressed");
}
});
Use an event filter and whatever keyevent you need, here I use ANY:
scene.addEventFilter(KeyEvent.ANY, keyEvent -> {
System.out.println(keyEvent);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With