Mohsin Mohsin - 4 months ago 114
Java Question

JavaFX TextField Validation

I want to validate whether the data input in the JavaFX TextField is integer or not. I want to do this validation only after the user completely writes the input and moves on to the next field.

Have tried an approach but it is not working, and I can't see why:

product_quantity.textProperty().addListener(new ChangeListener<String>() {
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
if (!product_quantity.isFocused()) {
if (!product_quantity.getText().matches("[0-9]*")) {
total_cost.setStyle("-fx-background-color: red;");
} else {
total_cost.setText(Float.toString(Float.parseFloat(newValue) * Float.parseFloat(unit_cost.getText())));
total_cost.setStyle("-fx-background-color: white;");

How can this be done?


Instead of adding a listener to textProperty(), you can add a listener to focusProperty(). This way the listener will be fired only when the TextField loses or receives focus.

textField.focusedProperty().addListener((observable, oldValue, newValue) -> {
    if(!newValue) { // we only care about loosing focus
       // check condition and apply necessay style