[英]KeyListener with JFormattedTextField
有人可以向我解释为什么getValue()
函数总是返回null
? 如果我使用getText()
而不是getValue()
那么一切都很完美,但我想要的是价值而不是文本。 我可以将它转换为整数,但我不认为这是最好的方法。
public class Test {
public static void main(String[] args) {
JFrame jf = new JFrame("test jftf");
jf.setSize(100, 100);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
JFormattedTextField jftf = new JFormattedTextField(NumberFormat.getIntegerInstance());
jftf.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
System.out.println(jftf.getValue());
}
});
jf.add(jftf);
}
}
如果您依赖于getValue()
方法,则需要确保已提交当前编辑。 您可以通过调用方法commitEdit()
来执行此操作,否则您可能无法获得您期望的值:
@Override
public void keyReleased(KeyEvent e) {
//Forces the current value to be taken from the AbstractFormatter
//and set as the current value:
try {
jftf.commitEdit();
} catch (ParseException e1) {
//Handle possible parsing error...
}
System.out.println(jftf.getValue());
}
这是一个示例,说明这是如何工作的值的名称不准确。 想想这样。 JFormattedTextField有一个名为lastValidInt的字段,它包含一个整数。 每次格式化字段中的文本时,程序将检查字段中的文本是否为数字。 如果是,那么lastValidInt将被设置为该字符串。
getValue()
方法将检查lastValidInt是否已初始化,如果已经初始化,则返回lastValidInt的值。 如果没有则返回null 。
示例:这些假设您每次都在重新启动应用程序。 输入是您将在该字段中编写的内容。 输出是控制台在输入内容后打印的内容。
1:
Input: a
Ouput: null
//a is not a number therefore the output is null
2:
Input: 1
Output: 1
//1 is a number therefore the output is 1
3:
Input1: a
Ouput: null
Input2: as
Ouput: null
Input3: asd
Ouput: null
Input4: asdf
Ouput: null
//a is not a number therefore the output is null
4:
Input1: 1
Ouput: 1
Input2: 1f
Ouput: 1
//The first thing the was read here was 1 therefore lastValidInt was set to 1 then the next input is 1f which is not a number therefore lastValidInt remained 1
5:
Input1: f
Ouput: null
Input2: f1
Ouput: null
//f is not a number therefore output is null, f1 is not a number either since it has a character that is not a digit and therefore lastValidInt has not been initialized
6:
Input1: f
Ouput: null
Input2:
Output: null
Input3: 1
Output: 1
Input4: 1f
Output: 1
//f is not a number therefore output is null, "" is also not a number therefore output is null again then the only thing that exists in the field is 1 which is a number therefore output is 1, finally by adding a f the field is no longer a number so output is same as before.
7:
Input1: f
Ouput: null
Input2: 1f (moved back to the begining without erasing f)
Output: null
//f is not a number therefore output is null, 1f is not a number either since it has a character that is not a digit and therefore lastValidInt has not been initialized
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.