问题描述
运行此代码时:
JTextField ansTxt;
...
ansTxt = new JTextField(5);
String aString = ansTxt.getText();
int aInt = Integer.parseInt(aString);
为什么会出现此错误?
更新:
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构造函数实际上是 width 列数.从文档中:
The integer argument to the JTextField constructor is actually the width in number of columns. From the docs:
使用指定的列数构造一个新的空TextField.将创建一个默认模型,并将初始字符串设置为null.
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",请输入
you'll basically get an empty text-field (slightly wider than if you constructed it using no-argument constructor). If you want it to contain the string "5" you should write
ansTxt = new JTextField("5");
更新:IIRC,您将为keyDown获得一个事件,为keyTyped获得一个事件,并为keyUp获得一个事件.推测文本字段尚未在keyDown事件上更新.无论哪种方式,我建议您将Integer.parseInt封装在
Update:IIRC, you'll get one event for keyDown, one for keyTyped, and one for keyUp. Presumably the text-field has not yet been updated on the keyDown event.Either way I suggest that you encapsulate the Integer.parseInt in a
try { ... } catch (NumberFormatException e) { ... }
这篇关于java.lang.NumberFormatException:对于输入字符串:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!