2012-10-17 81 views
0

在我的jTable中,第一列包含一個數值。當我選擇「添加行」的下一行運行該代碼:異常拋出我的自定義添加行代碼

DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); 
int x = jTable1.getRowCount(); 
String cellValue = ""; 
if(x > 0){ 
    java.lang.Object cell = jTable1.getValueAt(x,0); 
    int a = Integer.parseInt(cell.toString()); 
    int b = a + 1; 
    cellValue = Integer.toString(b); 
} 

java.lang.Object[] os = new Object[]{cellValue,"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",}; 
model.addRow(os); 
jTable1.setModel(model); 
jTable1.setAutoCreateColumnsFromModel(true); 

這段代碼的一點是要添加新行,但新行中的第一個值將被填掉。這是關鍵的數字。不幸的是,關鍵號碼與行數無關。

當jButton按下「添加行」時,它會拋出這個異常。

在異常線程 「AWT-EventQueue的-0」 java.lang.ArrayIndexOutOfBoundsException:837> = 837

數目是有意義,因爲837是行JTable中具有的數量時,我的推按鈕。

感謝您提前提供任何幫助。

+0

這是很清楚的說,它期待數小於837,即836 ...還怎麼了用「」,};最後。 – dngfng

+0

此外,它看起來像一個非常糟糕的方式來做你想做的事情 - 你使用的是什麼API? – dngfng

+0

我沒有注意到我做到了。 –

回答

0

這映射到Vector.size()DefaultTableModel

int x = jTable1.getRowCount(); 

這映射到Vector.get(int index)

java.lang.Object cell = jTable1.getValueAt(x,0); 

Vector.get(int index)隔空仔細觀察就會發現:

拋出:ArrayIndexOutOfBoundsException異常 - 指數超出範圍(索引< 0 || index> = size())。

現在自x == size()引發異常。

這應該可以解決這個問題:

java.lang.Object cell = jTable1.getValueAt(--x,0); 
+0

謝謝!我會試試這個。 –