0

I've searched for a while now and couldn't find anything for my exact problem. I am trying to force the User to only put double values e.g 0.35, 4.35, 44.35, 444.35, 4444.35 into a TextField. For simple Numbers I already found a working solution.

public class IntegerTextField extends TextField {
private static Pattern integerPattern = Pattern.compile("[0-9]*");
@Override
public void replaceText(int start, int end, String text) {
    if (validate(text)) {
        super.replaceText(start, end, text);
    }
}
@Override
public void replaceSelection(String text) {
    if (validate(text)) {
        super.replaceSelection(text);
    }
}
private boolean validate(String text) {
    return integerPattern.matcher(text).matches();
}

}

Now I am trying to do the same for double values, but I don't know how to adjust this to work for doubles too. What I am trying to do now, was to add a Listener on the TextField and check if the regex matches the text.

myTxtField.textProperty().addListener((observable, oldValue, newValue) -> {
        if (!newValue.matches("some regex here")) {
            myTxtField.setText(oldValue);
        }
    });
}

I've tried multiple regex that I've found on stackoverflow but the problem with all of them were either I couldn't clear the TextField completely, e.g if the User makes a wrong input on the first number, it needs to be deleted, to put a completely new number in. Or they were just not matching the exact numbers I need to.

I hope this is clear enough, thank you for your help. I am working with Java 8.

siggi_n
  • 9
  • 1
  • 2
    See eden coding’s: [JavaFX TextField – everything you need to know](https://edencoding.com/javafx-textfield/). Look at the sections on TextFormatter, UnaryOperator and testing for numbers. – jewelsea Nov 20 '21 at 19:27
  • I’m curious, what reference did you use to come up with your current strategy rather than using a text formatter? – jewelsea Nov 20 '21 at 21:23
  • The two basic forms are `(?:\d+(?:\.\d*)?|\.\d+)` for a final validation, and `(?:\d+(?:\.\d*)?|\.(?:\d+)?)` for character event handlers. Any variations or anything in between are handled on a case by case basis as are needed, and are simple. The validation regex is an example of _all_ decimal input's supported by atod() et all. There is no spacing in the regex but can be added, which are stripped by the function. – sln Nov 20 '21 at 22:20
  • Also consider a `Spinner` or `Slider`, for [example](https://stackoverflow.com/a/55427307/230513). – trashgod Nov 20 '21 at 22:21
  • @jewelsea I remember seeing a couple of things like this in JavaFX 2, before `TextFormatter` was introduced. – James_D Nov 20 '21 at 23:53

0 Answers0