问题描述
我正在寻找Swing InputVerifier替代JavaFX TextField.
I am looking for an alternative of Swing InputVerifier to JavaFX TextField.
Swing InputVerifier将阻止输入进行验证.
The Swing InputVerifier will prevent input that does verify.
考虑以下Swing JTextField代码:
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);
我可以使用TextField.setOnKeyTyped或TextField.textProperty的侦听器来检查键入的文本.但是,这不会阻止无效文本进入TextField.但是,我可以删除无法验证的键入文本,但这不是一个好的解决方案.
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.
解决方案:正如James_D所建议的那样,带有过滤器的TextFormatter是完美的解决方案
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));
推荐答案
首先由 James_D 建议 TextFormatter .
TextField instance = new TextField();
UnaryOperator<Change> textFilter = change -> {
String input = change.getText();
if (!change.isContentChange()) {
return change;
}
if (!myRegExTool.matches(input)) {
return null;
}
return change;
};
instance.setTextFormatter(new TextFormatter<String>(textFilter));
这篇关于JavaFX TextField:Swing InputVerifier的替代方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!