通过JTable从ArrayList中删除项目

时间:2015-04-23 02:10:38

标签: java swing arraylist error-handling jtable

我有一个JTable,其中包含来自ArrayList的内容,但每当我尝试从ArrayList删除已删除行的内容时,我都会IndexOutOfBoundsException取决于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(); }); 我想删除的行数及其位置。我该如何解决这个问题?

可运行代码:http://pastebin.com/Nnrnxzdg

<input type="button" value="a" onclick="searchLetter(this)"></input>

1 个答案:

答案 0 :(得分:3)

基本上,当你删除一行时,所有索引都会改变。所以你需要做的是复制所有选定的行,但不是索引,而是实际的行值......

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);
    }
}

没有关心价值指数是什么。