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:

@FXML
Text Field theTextField;

@FXML
Button theButton;

@FXML  
void ButtonPressed() {
    //do stuff here
}

@FXML
//when ENTER is pressed the button is activated
void textFieldEnterPressed() {
    ButtonPressed();
}
有帮助吗?

解决方案

In your FXML file, add a onKeyPressed handler

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

Implement the handler in you Controller

@FXML
public void handleEnterPressed(KeyEvent event)
    if (event.getCode() == KeyCode.ENTER) {
        // do some actions 
    }
}

其他提示

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

@FXML
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" ... />
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top