我收到以下错误消息。
java.lang.ArrayIndexOutOfBoundsException: 21 >= 21
at java.util.Vector.elementAt(Vector.java:427)
at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:277)
at com.vanuston.medeil.uitables.PurchaseTable.createTable(PurchaseTable.java:182)
at com.vanuston.medeil.ui.Purchase.applyDefaults$(Purchase.fx:130)
在下面代码的第三行。
jTable.removeColumn(jTable.getColumnModel().getColumn(19));
jTable.removeColumn(jTable.getColumnModel().getColumn(20));
jTable.removeColumn(jTable.getColumnModel().getColumn(21));
jTable.removeColumn(jTable.getColumnModel().getColumn(22));
我已经将第 21 列和第 22 列添加到 DefaultTableModel
中。
Vector cols = new Vector();
Vector data = new Vector();
int len = colName.length;
System.out.println("col length " + len);
for (int i = 0; i < initRow; i++) {
Vector c = new Vector();
for (int j = 0; j < len; j++) {
if (j == 19 && j == 20) {
c.addElement(Boolean.FALSE);
} else {
c.addElement(null);
}
}
data.addElement(c);
}
for (int n = 0; n < len; n++) {
cols.addElement(colName[n]);
System.out.println(colName[n]);
}
try {
jTable.setModel(new javax.swing.table.DefaultTableModel(data, cols) {
Class[] type = types;
boolean[] canEditCol = canEditCols;
@Override
public Class getColumnClass(int columnIndex) {
return type[columnIndex];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEditCol[columnIndex];
}
});
但我不知道,显示 ArrayIndexOutOfBounds
异常的原因是什么。
最佳答案
好吧,你打电话JTable.removeColumn
,列数组的每一列都被重新索引。例如,当删除元素 0 时,索引 1 处的元素现在会在索引 0 处重新索引。
您需要以相反的顺序删除这些列,以便不会发生这种重新索引:
jTable.removeColumn(jTable.getColumnModel().getColumn(22));
jTable.removeColumn(jTable.getColumnModel().getColumn(21));
jTable.removeColumn(jTable.getColumnModel().getColumn(20));
jTable.removeColumn(jTable.getColumnModel().getColumn(19));
您还可以调用以下行 4 次:
jTable.removeColumn(jTable.getColumnModel().getColumn(19));
由于每次调用 i
时,19 + i
列将变为第 19 列。
关于java.lang.ArrayIndexOutOfBoundsException : 21 >= 21,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32841823/