【发布时间】:2012-04-17 18:22:20
【问题描述】:
所以我正在为 JTextField 编写 TextValueChanged 处理程序,该处理程序需要很长时间才能输入。它只需要允许用户输入介于 0 和 Long.MAX 之间的有效值。如果用户键入了一个无效字符,它应该去掉它,以便 JTextField 中的值始终是一个有效的 long。
我当前的代码看起来像这样,但看起来很难看。没有外部库(包括 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) 调用中重新填充,因此要“存储”该值,只需将其传递给该调用即可。
【问题讨论】:
-
改用
JFormattedTextField有什么问题? -
我可以这样做,但它的行为与我想要的不符。如果失去焦点,您要么丢失更改并恢复到以前保存的文本(我不想要),要么保留无效文本(我也不想要)。要强制这种行为,我只需要覆盖它并在不同的事件中编写一些代码。
-
JFormattedTextField的问题是你可以输入任何你喜欢的东西。只有在您退出文本字段后才会进行验证。
标签: java swing jtextfield formatted-input