因此,我正在为 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) 调用中重新填充,因此要“存储”该值,只需将其传递给该调用即可。