ArrayIndexOutOfBoundsException:每个

时间:2015-08-05 01:32:11

标签: java foreach jtable indexoutofboundsexception

我是Java的新手,我编写了一个使用一些JTable的程序。 我有一个按钮来删除选定的行,执行此操作:

public static void removerows() {
    int[] row_indexes = TableCA.table.getSelectedRows();
    for(int i=0;i<row_indexes.length;i++) {
        TableCA.model.removeRow(row_indexes[i]);
    }
}

但是当它执行时,我收到此错误:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2 >= 1
    at java.util.Vector.removeElementAt(Vector.java:554)
    at javax.swing.table.DefaultTableModel.removeRow(DefaultTableModel.java:463)
    at fr.diagamma.project.PanelCaisse.removerows(PanelCaisse.java:78)

我搜索了很多,而且我没有找到任何针对OutOfBounds案例的内容。 谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

我的建议是你颠倒循环的顺序:

public static void removerows() {
    int[] row_indexes = TableCA.table.getSelectedRows();
    for(int i=row_indexes.length - 1; i >= 0; i--) {
        TableCA.model.removeRow(row_indexes[i]);
    } 
}

这从最后一个元素开始,直到它到达第一个元素为止。

因为,除非你的row_indexes只有1个元素,否则它有两种错误:

  1. row_indexes之后的removeRow()中的索引不再更新。
  2. 如果row_indexes处于递增顺序,则很容易引发OutOfBoundException。