While typing in a text field enable a keystroke ENTER to activate a button in JavaFX


Such as typing into the Google search box the hitting ENTER activates the search

I've just been introduced to JavaFX and Scene Builder a few days ago so I'm learning the basics here. I have the latest version of JavaFX and am using Scene Builder to facilitate action events. Also, any pointers to relevant tutorials would be helpful. At one point in the day I was focused on the Keyboard section of the coding panel of Scene Builder, especially with the "On Key Released" event with no results. Thanks in advance

Here's a rough idea of what I'm trying to do:

Text Field theTextField;

Button theButton;

void ButtonPressed() {
    //do stuff here

//when ENTER is pressed the button is activated
void textFieldEnterPressed() {
8/29/2013 7:09:43 PM

Accepted Answer

In your FXML file, add a onKeyPressed handler

 <TextField fx:id="yourTextField" onKeyPressed="#handleEnterPressed">

Implement the handler in you Controller

public void handleEnterPressed(KeyEvent event)
    if (event.getCode() == KeyCode.ENTER) {
        // do some actions 
3/25/2015 12:48:38 PM

In TextField, when you press Enter, you get notification through onAction. In your Java code you can add:

private void handleTFAction(ActionEvent event) {
    TextField source = (TextField)event.getSource();
    System.out.println("You entered: "+source.getText());

In your FXML (or through JavaFX SceneBuilder designer) hook it up to your TextField's OnAction event. In FXML it looks something like this:

<TextField onAction="#handleTFAction" ... />

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow