0

i tried limited my javafx TextField for letters and max length. I've done it many times before and i always used the same method but this time i had error.

This is my code:

nameTextField.textProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(final ObservableValue<? extends String> ov, final String oldValue, final String newValue) {
            if (nameTextField.getText().length() > 30) {
                String s = nameTextField.getText().substring(0, 30);
                nameTextField.setText(s);
            }
            if (!newValue.matches("\\sa-zA-Z")) {
                nameTextField.setText(newValue.replaceAll("[^\\sa-zA-Z]", ""));
            }
        }
    });

When i use only limit for maxlength it's work correct and when i use only limit for type of letters also work correct. But when i use both limit on one field don't works correct.

Limit for type of letters work correct but when i try put more than 30 letter i have "Exception in thread "JavaFX Application Thread" java.lang.StackOverflowError"

at this line

nameTextField.setText(newValue.replaceAll("[^\\sa-zA-Z]", ""));
Boker
  • 61
  • 3
  • 4
    Changing the value of an observable from a listener added to said observable is not ideal. Anyways, you should be using a [`TextFormatter`](https://openjfx.io/javadoc/13/javafx.controls/javafx/scene/control/TextFormatter.html). – Slaw Dec 12 '19 at 10:36
  • This [answer](https://stackoverflow.com/a/40472822/6028807) uses `UnaryOperator` to solve a similar problem. – Miss Chanandler Bong Dec 12 '19 at 15:53

1 Answers1

0

There's a problem in your regex matching function.

It always goes inside the second if and replace the string with a new one even if it goes beyond the limits.

So it's setting the text with over limits chars then a change event is emitted again and so on... that is the reason of a stackoverflow exception.

you should put this

 if (!newValue.matches("[a-zA-Z]+")) 

and for best practices you might use else if instead of second if

because it is impossible to achieve the two conditions.

Community
  • 1
  • 1
ABD ALHADI
  • 71
  • 3