我有多个TextFields
,我正在尝试查找用户输入到其中的数字的总和。
credit1.textProperty().addListener(new creditChangeListener(this.credit1, this.course1, this.grade1));
credit2.textProperty().addListener(new creditChangeListener(this.credit2, this.course2, this.grade2));
credit3.textProperty().addListener(new creditChangeListener(this.credit3, this.course3, this.grade3));
credit4.textProperty().addListener(new creditChangeListener(this.credit4, this.course4, this.grade4));
我有一个内部类实现
ChangeListener
来处理每个TextField
的用户输入。 private class creditChangeListener implements ChangeListener<String>{
private final TextField credit;
private final TextField course;
private final TextField grade;
public creditChangeListener(TextField credit, TextField course, TextField grade){
this.credit = credit;
this.course = course;
this.grade = grade;
}
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){
if(!credit.getText().matches("[0-9]+")) grade.setText("");
if(!course.getText().isEmpty() && !grade.getText().isEmpty()) {
addSum();
}
}
private void addSum(){
sum += Integer.parseInt(credit.getText());
System.out.println("Current sum: " + sum);
}
}
我需要找到输入到这些
credit TextFields
中的数字的总和,但是ChangeListener
逐位添加数字,而我需要输入完整的数字。我曾想过在ChangeListener
失去焦点之后触发TextFields
,但是我无法找到实现该目标的方法,也不知道这是正确的方法。 最佳答案
不久前,我遇到了同样的问题,我解决了这个问题,在Focused属性中添加了一个Listener,而不是Changed属性。首先创建一个可以重用的监听器:
private ChangeListener<Boolean> focusListener = new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (!newValue) {
sum(); //Do the sum logic here!!!
}
}
};
然后将更改侦听器应用于所有文本字段
credit1.focusedProperty().addListener(focusListener);
credit2.focusedProperty().addListener(focusListener);
credit3.focusedProperty().addListener(focusListener);
credit4.focusedProperty().addListener(focusListener);
您可以以这种方式实现内部类,以在每次
Textfield
失去焦点时触发事件。希望能帮助到你...