所以我正在为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 = …Run Code Online (Sandbox Code Playgroud)