Eduard Nickel
Eduard Nickel

Reputation: 155

How disable move focus from textField in JavaFX

Is there possibility to keep focus on textField in JavaFX? I do validation on textField using listener.

textField.textProperty().addListener(
        new ChangeListener<String>() {
        @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                if (!validate(newValue)) {
                    textField.setStyle("-fx-text-fill: green;");
                    textField.requestFocus();
                } else {
                    textField.setStyle("-fx-text-fill: black;");
                }
            }
        }
    );

It is function which returns boolean depending on textField value validity. If value is not valid then I change text color to RED. Then I want to keep focus on invalid textField and force user to correct value. Can it be done? Thanks in advance.

Upvotes: 0

Views: 896

Answers (1)

fabian
fabian

Reputation: 82451

Also use a listener for the focused property which takes back the focus, when it's moved somewhere else:

ChangeListener<Boolean> focusLossListener = (observable, wasFocused, isFocused) -> {
    if (!isFocused) {
        tf.requestFocus();
    }
};
textField.textProperty().addListener(
        new ChangeListener<String>() {
        @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                textField.focusedProperty().removeListener(focusLossListener);
                if (!validate(newValue)) {
                    textField.focusedProperty().addListener(focusLossListener);
                    textField.setStyle("-fx-text-fill: green;");
                    textField.requestFocus();
                } else {
                    textField.setStyle("-fx-text-fill: black;");
                }
            }
        }
    );

Upvotes: 2

Related Questions