所以我正在为JTextField编写TextValueChanged处理程序,它需要很长的输入。它只需要允许用户输入介于0和Long.MAX之间的有效值。如果用户键入了无效字符,则应将其删除,以使JTextField中的值始终为有效长。
我目前的代码看起来像这样,但看起来很难看。没有外部库(包括Apache Commons),有没有更清晰/更简单的方法呢?
public void textValueChanged(TextEvent e) {
if (e.getSource() instanceof JTextField) {
String text = ((JTextField) e.getSource()).getText();
try {
// Try to parse cleanly
long longNum = Long.parseLong(text);
// Check for < 1
if (longNum < 1) throw new NumberFormatException();
// If we pass, set the value and return
setOption("FIELDKEY", longNum);
} catch (NumberFormatException e1) {
// We failed, so there's either a non-numeric or it's too large.
String s = ((JTextField) e.getSource()).getText();
// Strip non-numeric characters
s = s.replaceAll("[^\\d]", "");
long longNum = -1;
if (s.length() != 0) {
/* Really ugly workaround for the fact that a
* TextValueChanged event can capture more than one
* keystroke at a time, if it's typed fast enough,
* so we might have to strip more than one
* character. */
Exception e3;
do {
e3 = null;
try {
// Try and parse again
longNum = Long.parseLong(s);
} catch (NumberFormatException e2) {
// We failed, so it's too large.
e3 = e2;
// Strip the last character and try again.
s = s.substring(0, s.length() - 1);
}
// Repeat
} while (e3 != null);
}
// We parsed, so add it (or blank it if it's < 1) and return.
setOption("FIELDKEY", (longNum < 1 ? 0 : longNum));
}
}
}
该字段不断从getOption(key)调用重新填充,因此要“存储”该值,只需将其传递给该调用。
答案 0 :(得分:6)
DocumentFilter是一个很好的解决方案。
John Zukowski的The Definitive Guide to Java Swing在第542-546页上有一个很好的例子,显示了一个用于限制整数范围的自定义文档过滤器。
提供自定义DocumentFilter应该可以轻松满足在复制/ pase中删除不需要的字符的要求,如您在其中一条评论中指定的那样。
答案 1 :(得分:2)
答案 2 :(得分:0)
我有这个用于长期
的浮动class DoubleTextDocument extends PlainDocument {
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if (str == null)
return;
String oldString = getText(0, getLength());
String newString = oldString.substring(0, offs) + str
+ oldString.substring(offs);
try {
Float.parseFloat(newString + "0");
super.insertString(offs, str, a);
} catch (NumberFormatException e) {
}
}
}
在您的扩展JTextField
中,您可以使用
@Override
protected Document createDefaultModel() {
return new DoubleTextDocument();
}