I am making registration form in JavaFX. And i have button to submit entered data, which works perfectly. But i also want to allow user to submit data when user press enter ?
Is there any way to combine in one if statement if button is pressed or enter is pressed ?
I know i can make it separately but then i need to double my code.
You have to listen to key press events and button press events separately, there is no way to handle these two events with a single listener: the button press will fire an ActionEvent
and the key press will file a KeyEvent
.
But, if you create a method to make the "data submission" and you simply call this method in the two listeners, you can avoid code duplication.
submitButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
submitData();
}
});
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent ke) {
switch (ke.getCode()) {
case ENTER:
submitData();
break;
default:
break;
}
}});
Or the same in a short form using lambdas:
submitButton.setOnAction(event -> submitData());
scene.setOnKeyPressed(keyEvent -> {
if(keyEvent.getCode().equals(KeyCode.ENTER))
submitData();
});