I have multiple TextFields
and i'm trying to find the sum of the numbers entered into them by the user.
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));
I have an inner class implementing ChangeListener
to handle user input for each 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);
}
}
I need to find the sum of the numbers entered into those credit TextFields
, however the ChangeListener
adds digit by digit while i need the whole number entered. I thought of triggering the ChangeListener
after the TextFields
lose focus, but i couldn't find out how to achieve that nor am I sure that it is the proper way of doing it.