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.