[英]Empty or not parsable input -> field border gets red
我有以下代码检查输入是否为Long
变量:
public void validateTextFieldLong (TextField textField, PseudoClass errorClass){
textField.focusedProperty().addListener((arg0, oldValue, newValue) -> {
try {Long.parseLong(textField.getText().trim());
textField.pseudoClassStateChanged(errorClass, false);
}
catch (NumberFormatException e){
System.out.println(e);
textField.pseudoClassStateChanged(errorClass, true);
}
});}
而这个用于在失去焦点时检查空白字段
public <T extends Node> void validateNodeForEmptyByPredicate(
T node,
PseudoClass errorClass,
Predicate<T> predicate
) {
node.focusedProperty().addListener((arg0, oldValue, newValue) -> {
if (!newValue) {
node.pseudoClassStateChanged(errorClass, predicate.test(node));
}
});
}
它们不能一起使用,当变量不是Long时,聚焦时边框为红色,但是失去焦点时,即使输入不可解析,边框也不为红色。
如何以相同的方法检查空字段和不可解析的值,并在字段为空或不可解析时实现边框为红色?
这就是我解决的方法。 如果有人有更好的解决方案,请向我们展示。
private boolean isParsable = false;
public void validateTextFieldLong2 (TextField textField, PseudoClass errorClass){
textField.focusedProperty().addListener((arg0, oldValue, newValue) -> {
try {Long.parseLong(textField.getText().trim());
isParsable = true;
}
catch (NumberFormatException e){
System.out.println(e);
isParsable = false;
}
if (!newValue) { //when focus lost
if(textField.getText().trim().isEmpty() || !isParsable){
textField.pseudoClassStateChanged(errorClass, true);
}
else textField.pseudoClassStateChanged(errorClass, false);
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.