I am using a DocumentFilter
on a JTextField
which is used to enter in the amount of time an employee has worked. the filter is to ensure that the limit of input is only 4 characters long and to only allow numbers. A decimal may or may not be used but should only be allowed to be entered once, once a decimal is entered, there should only allow for one more number. Meaning 9.5 or 10.5 should be accepted and 8.45 is not.
So far I am able to get about half of the total desired functionality. No more than 4 characters can be entered and only digits are allowed. The latter is accomplished using the replaceAll("[^0-9.]", "")
method.
I've spent a lot of time watching tutorials, reading documentation and related questions such as this, this, and especially this, but can't seem to get a regex to perform fully. One thing in particular than I can't figure out is why exactly a regex of [^0-9]
will successfully only allow digits, but ^\d
wont unless enclosed as a character class such as [\d]
My filter code is below:
import java.awt.Toolkit;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class TimeWorkedFilter extends DocumentFilter {
private int maxCharacters;
public TimeWorkedFilter(int maxChars) {
maxCharacters = maxChars;
}
//"[^0-9.]
public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)
throws BadLocationException {
if ((fb.getDocument().getLength() + str.length()) <= maxCharacters)
super.insertString(fb, offs, str.replaceAll("[^0-9.]", ""), a);
else
Toolkit.getDefaultToolkit().beep();
}
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a)
throws BadLocationException {
if ((fb.getDocument().getLength() + str.length()
- length) <= maxCharacters)
super.replace(fb, offs, length, str.replaceAll("[^0-9.]", ""), a);
else
Toolkit.getDefaultToolkit().beep();
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…