Reputation: 33
Okay, i'm currently designing a GUI in JavaFX. i have a text box that needs to allow for doubles. It currently allows for doubles, but it allows the user to still add multiple decimals
what I want: 92.8123
what i don't want: 92..5.78
I've tried to fiddle around with it, but I don't understand regular expressions enough to limit the text box to what I want properly.
tpo.textProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue.matches("\\d*")) tpo.setText(newValue.replaceAll("[^\\d.]", ""));
});
tpo is the name of the text box
Upvotes: 2
Views: 159
Reputation: 4699
I think this might do what you want:
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
...
TextField tpo = ...;
tpo.setTextFormatter(new TextFormatter<>((change) -> {
String text = change.getControlNewText();
if (text.matches("\\d*\\.?\\d*")) {
return change;
} else {
return null;
}
}));
For every change applied to the TextField
, this will check what the new text would be and make sure it would match the given pattern. Since the user is likely entering characters one at a time (rather than pasting) we need to allow that the later part of the pattern might not yet be typed, so we need to allow zero or more digits after the dot, and if we want the user to be able to fully delete their input we need everything to be optional. You would need to check the final pattern on submission to verify they entered a full valid double.
Upvotes: 3