I am looking for an alternative of Swing InputVerifier to JavaFX TextField.
The Swing InputVerifier will prevent input that does verify.
Consider the following Swing JTextField code:
InputVerifier iv = new InputVerifier() {
/* (non-Javadoc)
* @see javax.swing.InputVerifier#verify(javax.swing.JComponent)
*/
@Override
public boolean verify(JComponent input) {
JTextField tf = (JTextField) input;
if (!myRegExTool.matches(tf.getText())) {
return false;
}
return true;
}
};
jinstance.setInputVerifier(iv);
I could use TextField.setOnKeyTyped or a listener to TextField.textProperty to check the typed text. However that will not prevent invalid text to get into the TextField. I could however delete typed text that does not verify, but that is not a good solution.
Solution: As suggested by James_D a TextFormatter with a filter was the perfect solution
UnaryOperator<Change> textFilter = change -> {
String input = change.getText();
if (!myRegExTool.matches(input)) {
return null;
}
return change;
};
instance.setTextFormatter(new TextFormatter<String>(textFilter));