I have some Text Field on a dialog when use input data in Text Field.
I want to check if the user pressed the enter key and, then, save this data. But, if the enter key is not pressed to set back to the old data.
Currently, I use javaFx to code.
I have some Text Field on a dialog when use input data in Text Field.
I want to check if the user pressed the enter key and, then, save this data. But, if the enter key is not pressed to set back to the old data.
Currently, I use javaFx to code.
I register a listener (here Java 8 lambda version) at the textfield:
filterTextField.setOnKeyReleased(event -> {
if (event.getCode() == KeyCode.ENTER){
// do what is to do
}
});
I know this is already an old thread but I hope this helps someone.
textField.setOnKeyPressed(new
EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if(event.getCode().equals(
KeyCode.ENTER)
) {
// do something
}
}
});
Very easy check this, the easiest way is go to your text field code in scene builder then give a name to " On Key Pressed " Keyboard Proprieties and paste the FXML method in your FXML Controller Class then add this:
@FXML
void the_name_of_the_method(KeyEvent event) {
if(event.getCode() == KeyCode.ENTER) {
do_what_ever_you_want_here();
}
}
In older version of Java you could write something like this: for example lets suppose you have a ComboBox<String>
with some random values... so you can simple add an event on that ComboBox (call it cBox
)
cBox.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent keyEvent) {
if (keyEvent.getCode().equals(KeyCode.ENTER)) {
// do what you want
}
}
});
But from Java 1.8 you can use lambda functions instead so you could replace the above code with this:
cBox.setOnKeyPressed(keyEvent -> {
if (keyEvent.getCode().equals(KeyCode.ENTER)) {
// do what you want
}
});
Don't forget to use equals
instead of ==
. (https://www.geeksforgeeks.org/difference-equals-method-java/)