Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pick up the Enter Key being pressed in JavaFX2?

I have a TextField to enter a search term, and a button for "Go". But in JavaFX2, how would I make it so pressing the Enter Key in the TextField would perform an action?

Thanks :)

like image 659
Geesh_SO Avatar asked Dec 14 '12 14:12

Geesh_SO


2 Answers

I'm assuming you want this to happen when the user presses enter only while the TextField has focus. You'll want use KeyEvent out of javafx.scene.input package and do something like this:

field.setOnKeyPressed(new EventHandler<KeyEvent>() {     @Override     public void handle(KeyEvent ke) {         if (ke.getCode().equals(KeyCode.ENTER)) {             doSomething();         }     } }); 

Using lambda:

field.setOnKeyPressed( event -> {   if( event.getCode() == KeyCode.ENTER ) {     doSomething();   } } ); 
like image 70
Brendan Avatar answered Sep 19 '22 08:09

Brendan


You can use the onAction attribute of the TextField and bind it to a method in your controller.

@FXML public void onEnter(ActionEvent ae){    System.out.println("test") ; } 

And in your FXML file:

<TextField fx:id="textfield" layoutX="29.0" layoutY="298.0" onAction="#onEnter" prefWidth="121.0" /> 
like image 28
Wottensprels Avatar answered Sep 22 '22 08:09

Wottensprels