我有一个 JTable
,其中包含 ArrayList
中的项目,但是每当我尝试从 ArrayList
中删除已删除行的内容时,我根据我要删除的行数及其位置获取 IndexOutOfBoundsException
。我该如何解决这个问题?
可运行代码:http://pastebin.com/Nnrnxzdg
remove.addActionListener( e -> {
int k = 0;
int[] rows = table.getSelectedRows();
TableModel tm= table.getModel();
while(rows.length>0)
{
while(k<rows.length)
{
al.remove(table.getSelectedRow() + k);
k++;
}
((DefaultTableModel)tm).removeRow(table.convertRowIndexToModel(rows[0]));
rows = table.getSelectedRows();
}
table.clearSelection();
});
最佳答案
基本上,当您删除一行时,所有索引都会发生变化。因此,您需要做的是复制所有选定的行,但不是索引,而是实际的行值...
JTable table = getTable();
if (table.getSelectedRowCount() > 0) {
List<Vector> selectedRows = new ArrayList<>(25);
DefaultTableModel model = getModel();
Vector rowData = model.getDataVector();
for (int row : table.getSelectedRows()) {
int modelRow = table.convertRowIndexToModel(row);
Vector rowValue = (Vector) rowData.get(modelRow);
selectedRows.add(rowValue);
}
现在有了这个,您可以使用模型计算任何给定对象的 indexOf
并将其删除...
for (Vector rowValue : selectedRows) {
int rowIndex = rowData.indexOf(rowValue);
model.removeRow(rowIndex);
}
}
不关心值的索引是什么。
关于java - 通过 JTable 从 ArrayList 中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29812387/