我试图让一些JTextFields只验证货币($ xxx.xx)这样的双数,我用DocumentFilter写了一个类来验证模式和字符的大小,但是我无法实现是用户可以键入多个点。
以下是我的代码示例:
private class LimitCharactersFilter extends DocumentFilter {
private int limit;
private Pattern regex = Pattern.compile( "\\d*(\\.\\d{0,2})?");
private Matcher matcher;
public LimitCharactersFilter(int limit) {
this.limit = limit;
}
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
throws BadLocationException {
String fullText = fb.getDocument().getText(0, fb.getDocument().getLength()) + string;
matcher = regex.matcher(fullText);
if((fullText.length()) <= limit && matcher.matches()){
fb.insertString(offset, string, attr);
}else{
Toolkit.getDefaultToolkit().beep();
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
throws BadLocationException {
String fullText = fb.getDocument().getText(0, fb.getDocument().getLength()) + text;
matcher = regex.matcher(fullText);
matcher = regex.matcher(text);
if((fullText.length()) <= limit && matcher.matches()){
fb.replace(offset,length, text, attrs);
}else{
Toolkit.getDefaultToolkit().beep();
}
}
}
验证字符的限制效果很好,但我想限制用户输入两位以上的数字(如果已有点)。
希望有人能帮助我。
答案 0 :(得分:2)
To allow the dot to be entered when typing a float number, you can use
\\d*\\.?\\d{0,2}
Note that here,
\\d*
- zero or more digits\\.?
- one or zero dots\\d+
- one or more digitsPlease also consider using VGR's suggestion:
new JFormattedTextField(NumberFormat.getCurrencyInstance());
This will create a text field that allows currency as input.