0

I found this link useful to make a JavaFX TextField accepts only numeric values. However I would like to simplify the solution so that it can be implemented on multiple TextFields.

Looking for something like :

ChangeListener<String> numericTextFieldListener = (observable, oldValue, newValue) -> {
    if(!newValue.matches("\\d*")) {
        //textField.setText(newValue.replaceAll("[^\\d]", "")); //how to set this new value to parent text field?
    }
};

textField1.textProperty().addListener(numericTextFieldListener);
textField2.textProperty().addListener(numericTextFieldListener);
textField3.textProperty().addListener(numericTextFieldListener);
textField4.textProperty().addListener(numericTextFieldListener);
// ... and so on

Any recommendation?

Community
  • 1
  • 1
pjRamores
  • 3
  • 2

1 Answers1

0

Method 1

You can simply make new class that implements ChangeListener and pass TextField as an argument in the constructor.

class MyChangeListener implements ChangeListener<String> {

    TextField txt;

    public MyChangeListener(TextField txt) {
        this.txt = txt;
    }

    @Override
    public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
        if (!newValue.matches("\\d*")) {
            txt.setText(newValue.replaceAll("[^\\d]", ""));
        }
    }
}

Now you can instantiate MyChangeListener and apply custom ChangeListener to your textFields like this.

textField1.textProperty().addListener(new MyChangeListener(textField1));
textField2.textProperty().addListener(new MyChangeListener(textField2));
textField3.textProperty().addListener(new MyChangeListener(textField3));

Method 2

You can make custom TextField like this.

class NumericalTextField extends TextField {

    public NumericalTextField() {
        super();
        addListener();
    }

    public NumericalTextField(String txt) {
        super(txt);
        addListener();
    }

    private void addListener() {
        this.textProperty().addListener((observable, oldValue, newValue) -> {
            if (!newValue.matches("\\d*")) {
                this.setText(newValue.replaceAll("[^\\d]", ""));
            }
        });
    }
}

and instantiate.

TextField txt1 = new NumericalTextField();
TextField txt2 = new NumericalTextField("Text");
Ashish
  • 325
  • 3
  • 9