In a JavaFX stage, I want to validate user input when the focus leaves a textfield. If the user input is not a valid age (0 to 120), then a Dialog using ControlsFX Dialogs with an error message is displayed.
Here's the code:
participantAgeTextField.focusedProperty()
.addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> ov,
Boolean oldPropertyValue, Boolean newPropertyValue)
{
if( !newPropertyValue ) { // lost focus
if( !participantAgeTextField.getText().isEmpty() ) {
if ( participantAgeTextField.getText().matches("^\\d+$")) {
int val = Integer.
parseInt(participantAgeTextField.getText());
if( val <= 0 ) {
val = 1;
} else if( val > 120 ) {
val = 120;
}
participantAgeTextField.setText(""+val);
} else {
participantAgeTextField.setText("");
Dialogs.create()
.owner(null)
.title("Error")
.masthead(null)
.message("You must enter a valid age!")
.showError();
}
}
}
}
});
This works fine, except when a user enters an invalid value, and then tries to close the window by clicking the "X" button in the top right corner of the window (stage).
In this case the application 'hangs'. (Strangely enough only in Windows, does not happen in Linux).
I have been looking for a fix, like not displaying the message when the focus changes to the window's "X". However I did not find a way to detect this.
Other ideas how to fix this would be greatly appreciated!
Joris
EDIT Probably ControlsFX causes the crash. I cannot use JavaFX dialogs (introduced in 8u40) because I'm using Javafx 8u25. Any alternatives welcomed!
EDIT 2 The crash can be avoided by not using ControlsFX Dialogs but creating the error message 'by hand' as suggested by DVarga. But this causes the error message to show up after the window has been closed. Any ideas on how to prevent that from happening?