运行这段代码时:
JTextField ansTxt;
...
ansTxt = new JTextField(5);
String aString = ansTxt.getText();
int aInt = Integer.parseInt(aString);
为什么会出现此错误?
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
更新:
JTextField ansTxt;
ansTxt = new JTextField(5);
ansTxt.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
ansTxt = (JTextField) e.getSource();
String aString = ansTxt.getText().trim();
int aInt = Integer.parseInt(aString);
}
}
最佳答案
JTextField constructor 的整数参数实际上是列数中的宽度。来自文档:
public JTextField(int columns)
Constructs a new empty TextField with the specified number of columns. A default model is created and the initial string is set to null.
通过构造它
ansTxt = new JTextField(5);
您基本上会得到一个空的文本字段(比使用无参数构造函数构造它时稍微宽)。如果您希望它包含字符串“5”,您应该这样写
ansTxt = new JTextField("5");
更新:
IIRC,您将获得一个针对 keyDown 的事件,一个针对 keyTyped 的事件,一个针对 keyUp 的事件。据推测,文本字段尚未在 keyDown 事件上更新。
无论哪种方式,我建议您将 Integer.parseInt 封装在
try { ... } catch (NumberFormatException e) { ... }
block ,因为用户很可能会写出整数以外的东西。
-->
关于java.lang.NumberFormatException : For input string: "" 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3701520/