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 的行数。

感谢您提前提供任何帮助。

4

1 回答 1

0

这映射到DefaultTableModel中的Vector.size()

int x = jTable1.getRowCount();

这映射到Vector.get(int index)

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

仔细查看Vector.get(int index) 会发现:

抛出: ArrayIndexOutOfBoundsException - 索引超出范围(索引 < 0 || 索引 >= size())。

现在因为x == size()抛出异常。

这应该可以解决问题:

java.lang.Object cell = jTable1.getValueAt(--x,0);
于 2012-10-17T10:01:24.507 回答