如何解决java swing中的JTF8DocumentFilter只允许数字有错误
我有一个 JTF8 DocumentFilter 类来让 Text 只接受数字(也有 (-) 数字),但是它有一个错误,因为它也允许我输入 (000) 或 (00)。我需要自定义它以拒绝输入 (00) 或 (000),并允许它像这样 (0) 那样在开头只输入一个零并拒绝它来生成像这样的数字 (02451)。
所以,当用户输入(0241)或(00241)时,它会自动变成(241)并拒绝他们在开头输入(0带数字)。
他们可以输入 (0) 但不能输入 (00) 或 (0345)!
我的班级是:
private static class JTF8DocumentFilter extends DocumentFilter {
int maxValue;
int minValue;
String text;
private JTF8DocumentFilter(int maxValue,int... optionalMinValue) {
this.maxValue = maxValue;
this.minValue = (maxValue - (maxValue * 2));
this.text = "";
if (optionalMinValue.length > 0
&& optionalMinValue[0] >= Integer.MIN_VALUE
&& optionalMinValue[0] < maxValue) {
this.minValue = optionalMinValue[0];
}
}
@Override
public void replace(DocumentFilter.FilterBypass fb,int i,int i1,String string,AttributeSet as) throws BadLocationException {
text += string;
int stringValue = 0;
if (!text.isEmpty() && text.matches("-?(\\d+)?")) {
if (text.length() == 1 && text.equals("-")) {
this.text = "-";
super.insertString(fb,text,as);
return;
}
try {
stringValue = Integer.parseInt(text);
} catch (NumberFormatException ex) {
super.remove(fb,fb.getDocument().getLength());
this.text = "";
// Toolkit.getDefaultToolkit().beep();
return;
}
} else {
super.remove(fb,fb.getDocument().getLength());
this.text = "";
// Toolkit.getDefaultToolkit().beep();
return;
}
if (string.matches("\\-|\\d") && (stringValue <= maxValue && stringValue >= minValue)) {
super.replace(fb,i,i1,string,as);
} else {
//System.out.println(stringValue);
if (stringValue > maxValue || stringValue < minValue) {
super.remove(fb,fb.getDocument().getLength());
this.text = "";
}
// Toolkit.getDefaultToolkit().beep();
}
}
@Override
public void remove(DocumentFilter.FilterBypass fb,int i1) throws BadLocationException {
super.remove(fb,i1);
this.text = fb.getDocument().getText(0,fb.getDocument().getLength());
}
@Override
public void insertString(DocumentFilter.FilterBypass fb,AttributeSet as) throws BadLocationException {
super.insertString(fb,as);
}
}
注意:这里的答案对我没有帮助,它仍然允许输入 (000) 而不是 (0) 一个零:DocumentFilter for negative and positive integer
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。