I have a class NumericTextField extends JTextField
.It only allows inputs based on a regex.What i need it to do is to only allow doubles.Most inputs if not all will be like 1
or 1.25
or 30.35
and so on.So it needs to only allow digits and only one decimal point.Till now i used a regex that allows more then one dot.
I tried a couple of regex like the following :
^\\d*(\\.\\d+)?$
\\d*(\\.)?\\d+
(?<=^| )\\d+(\\.\\d+)?(?=$| )|(?<=^| )\\.\\d+(?=$| )
[0-9]+(?:\\.[0-9]*)?
And many more.The problem is that it won't accept the dot(unless i copy-paste),it will only accept digits.I'm trying to input it via the >
key,my keyboard doesn't have a numeric keypad.Could that be the issue ? if so,how can i make it so that it only accepts one dot,the one near the letters,the >
one?
How can i fix this ?
Here is the class :
@SuppressWarnings("serial")
class NumericTextField extends JTextField {
@Override
protected Document createDefaultModel() {
return new NumericDocument();
}
private static class NumericDocument extends PlainDocument {
// The regular expression to match input against (zero or more digits)
private final static Pattern DIGITS = Pattern.compile("-?\\d+(\\.\\d+)?");
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
// Only insert the text if it matches the regular expression
if (str != null && DIGITS.matcher(str).matches()) {
super.insertString(offs, str, a);
}
}
}
}