Luis Inho
Luis Inho

Reputation: 1

JavaFX creating a textField event handler using lambda expressions that reacts to s specific key (enter)?

So, I got this that reacts to any key

TextField resultado = new TextField();
resultado.setOnKeyPressed(e -> System.out.println("It works!"))

But Would like it to react to return key only.

Anyone?

Thank You

Upvotes: 0

Views: 1831

Answers (2)

teraspora
teraspora

Reputation: 442

The way to find out the answers to these sorts of questions yourself is to delve into the Oracle documentation.

Thus, you are using method setOnKeyPressed() and this gives you a KeyEvent.

When you look up the instance methods on the KeyEvent class you find methods like getCharacter() and getCode().

You can then play around with these methods to figure out how they work and how you can use them.

In this way, you have then answered your own question and probably learnt more than you would just by posting a question here and waiting for someone to answer it. :)

Upvotes: 0

James_D
James_D

Reputation: 209358

TextField resultado = new TextField();
resultado.setOnKeyPressed(e -> {
    if (e.getCode() == KeyCode.ENTER) {
        System.out.println("It works!");
    }
});

Note that TextFields also fire action events when the enter key is pressed:

TextField resultado = new TextField();
resultado.setOnAction(e -> System.out.println("It works!"))

Upvotes: 2

Related Questions