Search code examples
javafxtextfieldscenebuilder

Text Field that accepts only numbers


Note: The Text Field I'm talking about below is an MFXTextField which I've got from MaterialFX.

I've searched a lot on how to make a Text Field in JavaFX that accepts only numbers. I've found many videos and posts but all of them didn't work for me, maybe because they are old and only worked in the past I don't really know about it.

So, I have a credit card Text Field and I need it to refuse letters or anything other than numbers. Here is my text field:

Text Field

Here is my code which accepts TextFormatter for regular TextField and refuses for MFXTextField:

        UnaryOperator<TextFormatter.Change> integerFilter = change -> {
            String newText = change.getControlNewText();
            if (newText.matches("-?([1-9][0-9]*)?")) {
                return change;
            }
            return null;
        };

        NormalTextField.setTextFormatter(
                new TextFormatter<>(new IntegerStringConverter(), null, integerFilter));

        CheckTextField.setTextFormatter(
                new TextFormatter<>(new IntegerStringConverter(), null, integerFilter));

Solution

  • Problem solved. All I had to do is replacing setTextFormatter with delegateSetTextFormatter and here is the new code:

            UnaryOperator<TextFormatter.Change> integerFilter = change -> {
                String newText = change.getControlNewText();
                if (newText.matches("-?([1-9][0-9]*)?")) {
                    return change;
                }
                return null;
            };
    
            MFXTextField.delegateSetTextFormatter(
                    new TextFormatter<Integer>(new IntegerStringConverter(), null, integerFilter));