-1

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));
Mohamad S.
  • 199
  • 1
  • 9
  • 3
    Research `TextFormatter`. – SedJ601 Apr 22 '22 at 22:02
  • 3
    https://stackoverflow.com/questions/40472668/numeric-textfield-for-integers-in-javafx-8-with-textformatter-and-or-unaryoperat – SedJ601 Apr 22 '22 at 22:03
  • 1
    Does this answer your question? [What is the recommended way to make a numeric TextField in JavaFX?](https://stackoverflow.com/questions/7555564/what-is-the-recommended-way-to-make-a-numeric-textfield-in-javafx) it has an updated answer with textformatter – Giovanni Contreras Apr 23 '22 at 00:20
  • I've just realized that maybe most of the solutions would have worked with a regular Text Field but I'm using a different type of text field. I've edited the post to explain this. – Mohamad S. Apr 23 '22 at 11:04
  • [mcve] demonstrating the not/working with a material / normal textField – kleopatra Apr 23 '22 at 12:08

1 Answers1

1

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));
Mohamad S.
  • 199
  • 1
  • 9