Search code examples
javauser-interfacejavafx-2javafx

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 :)


Solution

  • 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" />