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.
I had the same problem some time ago, I solved it adding a Listener to the Focused property instead the Changed property. First create a Listener you can reuse:
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!!!
}
}
};
Then apply the change listener to all your textfields
credit1.focusedProperty().addListener(focusListener);
credit2.focusedProperty().addListener(focusListener);
credit3.focusedProperty().addListener(focusListener);
credit4.focusedProperty().addListener(focusListener);
You can implement your inner class this way to trigger the event every time a Textfield
loses focus.
Hope it helps...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.