我有这段代码用于检查输入是否为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时,边框在聚焦时是红色的,但是当焦点丢失时,即使输入不可解析,边框也不是红色。
如何在同一方法中检查空字段而不是可解析的值,并在字段为空或不可解析时实现边框为红色?
答案 0 :(得分:0)
这就是我解决它的方式。如果有人有更好的解决方案,请告诉我们。
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);
}
});
}