TextField失去焦点时如何触发ChangeListener? JavaFX的

时间:2017-08-01 11:10:05

标签: java javafx

我有多个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,但我无法找到如何实现这一目标,也不确定这是否是正确的做法。

1 个答案:

答案 0 :(得分:3)

前段时间我遇到了同样的问题,我解决了为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失去焦点时触发事件。

希望它有所帮助...