Determine calling node inside JavaFX change listener

Viewed 7837

I need to perform validation on several TextFields when text is changed. The validation is exactly the same, so I thought I use a single procedure. I can't use onInputMethodTextChanged because I need to perform validation even when control does not have focus. So I added a ChangeListener to textProperty.

private TextField firstTextField;
private TextField secondTextField;
private TextField thirdTextField;

protected void initialize() {
    ChangeListener<String> textListener = new ChangeListener<String>() {
        @Override
        public void changed(ObservableValue<? extends String> observable,
                String oldValue, String newValue) {
            // Do validation
        }
    };

    this.firstTextField.textProperty().addListener(textListener);
    this.secondTextField.textProperty().addListener(textListener);
    this.thirdTextField.textProperty().addListener(textListener);
}

However, while performing validation, there is no way to know which TextField triggered the change. How can I obtain this information?

4 Answers

Just use valueProperty instead ;)

this.firstTextField.valueProperty().addListener(textListener);
this.secondTextField.valueProperty().addListener(textListener);
this.thirdTextField.valueProperty().addListener(textListener);

It has a simple solution.

public void setListener(TextField textField) {
    BiConsumer<TextField, String> check = (tField, newValue) -> {
        // Do validation
    };
    textField.textProperty().addListener((ov, o, n)->check.accept(textField, n));
}
Related