尝试将JTextField转换为int时的NumberFormatException

时间:2013-11-27 23:30:11

标签: java swing

在我的代码的这一部分中,我正在创建类Dizionario的对象并将其写入文件,首先调用construcor,接受3个参数,(Path,String,int)。 我从3个JTextField得到这3个参数,特别是最后一个(JTextField3)正在创建这个错误,转换为int

这是错误:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "javax.swing.JTextField[,62,11,302x28,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.synth.SynthBorder@9577f8b,flags=288,maximumSize=,minimumSize=,preferredSize=,caretColor=,disabledTextColor=DerivedColor(color=142,143,145 parent=nimbusDisabledText offsets=0.0,0.0,0.0,0 pColor=142,143,145,editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=DerivedColor(color=255,255,255 parent=nimbusSelectedText offsets=0.0,0.0,0.0,0 pColor=255,255,255,selectionColor=DerivedColor(color=57,105,138 parent=nimbusSelectionBackground offsets=0.0,0.0,0.0,0 pColor=57,105,138,columns=0,columnWidth=0,command=,horizontalAlignment=LEADING]"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.<init>(Integer.java:677)

我尝试使用这些代码将字符串转换为整数:

int i = new Integer(jTextField3.toString()); 

然后将i作为参数(或直接调用new Integer(...)作为参数)

(int)JTextField3.toString();

Integer.ParseInt(JTextField3.toString());

这是我的方法

    private void CreateMouseClicked(java.awt.event.MouseEvent evt) {                                    
    Dizionario dic = new Dizionario(
            (Paths.get(jTextField2.toString())),
            jTextField1.toString(),
            Integer.parseInt(jTextField3.toString())); 
    dic.writeToFile();
}   

2 个答案:

答案 0 :(得分:4)

嗯,它不是jTextField3.toString(),而是jTextField3.getText()。这是一个很大的区别,要查看toString()返回的内容,请查看您的错误消息。你试图解析这个:

"javax.swing.JTextField[,62,11,302x28,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.synth.SynthBorder@9577f8b,flags=288,maximumSize=,minimumSize=,preferredSize=,caretColor=,disabledTextColor=DerivedColor(color=142,143,145 parent=nimbusDisabledText offsets=0.0,0.0,0.0,0 pColor=142,143,145,editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=DerivedColor(color=255,255,255 parent=nimbusSelectedText offsets=0.0,0.0,0.0,0 pColor=255,255,255,selectionColor=DerivedColor(color=57,105,138 parent=nimbusSelectionBackground offsets=0.0,0.0,0.0,0 pColor=57,105,138,columns=0,columnWidth=0,command=,horizontalAlignment=LEADING]"

加入数字。

答案 1 :(得分:2)

请勿使用JTextField#toString,请使用JTextField#getText返回文字字段的文字内容,例如......

int i = new Integer(jTextField3.getText());

toString通常用于提供有关Object

的有用诊断信息