Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run a function on a specific key press in JavaFX?

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

like image 728
user2560035 Avatar asked Oct 19 '15 21:10

user2560035


People also ask

How do you check if a key is pressed in Javafx?

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.

What is getCode in Java?

getCode() The key code associated with the key in this key pressed or key released event. EventType<KeyEvent> getEventType()

What is ActionEvent Javafx?

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.


2 Answers

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");
    }
});
like image 104
James_D Avatar answered Oct 12 '22 01:10

James_D


Use an event filter and whatever keyevent you need, here I use ANY:

        scene.addEventFilter(KeyEvent.ANY, keyEvent -> {
            System.out.println(keyEvent);
        });
like image 29
Roland Avatar answered Oct 12 '22 00:10

Roland