gpt4 book ai didi

java - 验证多个输入字段时如何避免重复代码?

转载 作者:行者123 更新时间:2023-11-29 04:27:13 25 4
gpt4 key购买 nike

如何在验证多个输入字段(如 TextFieldDatePickerChoiceBoxes)时避免重复代码?下面这段代码属于 StageAddController 用来监听和验证输入的服务类。当焦点丢失且字段为空时,字段边框变为红色。

public void validateForEmptyTextField(TextField textField, PseudoClass errorClass){
textField.focusedProperty().addListener((arg0, oldValue, newValue) -> {
if (!newValue) { //when focus lost
if(textField.getText().trim().isEmpty()){
textField.pseudoClassStateChanged(errorClass, true);
}
else
textField.pseudoClassStateChanged(errorClass, false);
}
});
}

public void validateForEmptyDatePicker (DatePicker datePicker, PseudoClass errorClass){
datePicker.focusedProperty().addListener((arg0, oldValue, newValue) -> {
if (!newValue) { //when focus lost
if(datePicker.getValue() == null){
datePicker.pseudoClassStateChanged(errorClass, true);
}
else
datePicker.pseudoClassStateChanged(errorClass, false);
}
});
}

public void validateForEmptyChoiceBox (ChoiceBox<String > stringChoiceBox, PseudoClass errorClass){
stringChoiceBox.focusedProperty().addListener((arg0, oldValue, newValue) -> {
if (!newValue) { //when focus lost
if(stringChoiceBox.getValue() == null){
stringChoiceBox.pseudoClassStateChanged(errorClass, true);
}
else
stringChoiceBox.pseudoClassStateChanged(errorClass, false);
}
});
}

最佳答案

可以通过引入一个泛型参数T来实现延伸 Node (1) 并传递 Predicate<T> (2):

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)); // *
}
});
}
  • (1) 需要访问 focusedProperty方法;
  • (2) 它会决定是否 T是空的,例如:
    • TextField小号 -> field -> field.getText().trim().isEmpty() ;
    • DatePicker小号 -> picker -> picker -> picker.getValue() == null ;
    • ChoiceBox es -> box -> box.getValue() == null .

我想重写下面的代码块(*)

if (predicate.test(node)) {
node.pseudoClassStateChanged(errorClass, true);
} else {
node.pseudoClassStateChanged(errorClass, false);
}

进入:

node.pseudoClassStateChanged(errorClass, predicate.test(node));

关于java - 验证多个输入字段时如何避免重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45652509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com