2013-11-27 103 views
1

在我的代碼的這一部分中,我創建了類Dizionario的一個對象,並將其寫入文件,首先調用construcor,接受3個參數(Path,String,int )。 我正在從3的JTextField和格外,最後一個(JTextField3)這3個參數是創建這個錯誤,轉換成intNumberFormatException在嘗試將JTextField轉換爲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,[email protected],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作爲參數(或直接致電新的整數(...)作爲參數)

(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(); 
} 
+0

有用的診斷信息* 「嘗試將JTextField轉換爲int時的NumberFormatException」* betterApproach ='JSpinner' +'SpinnerNumberModel'。 –

回答

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,[email protected],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]" 

成數字。

+0

但爲什麼我不會在第一個和第二個參數中遇到錯誤? – maxpesa

+1

@maxpesa你爲什麼要這樣? 'getText'和'toString'都返回'String',就編譯器而言,它們是該方法的正確選項......編譯器無法猜測調用的結果可能是什麼...... – MadProgrammer

+0

@maxpesa :因爲他們是絃樂隊。您應該測試您在println語句中獲得的字符串以查看您自己。 –

2

不要使用JTextField#toString,使用JTextField#getText返回文本字段的文本內容,例如...

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

toString通常用於提供有關Object

相關問題