I have a JTable and a button next to it that calls deleteSelectedRows()
, which does exactly what it sounds like:
public void deleteSelectedRows() { int[] selected = jTable.getSelectedRows(); for(int i = selected.length - 1; i >= 0; i--) { model.removeRow(selected[i]); } if(model.getRowCount() < 1) { addEmptyRow(); } }
But if a cell was in the act of being edited when it (and/or cells above it) were deleted, the edited cell stayed while the rest left, like this:
And then trying to exit out of the editing threw an ArrayIndexOutOfBoundsException
since row 5 was trying to be accessed and there was only one row left in the table.
I then tried all sorts of fun and games with jTable.getEditingRow()
. At first, adding an if(selected[i] != editing)
before the removal seemed to work, but then removing rows above the edited cell caused problems.
Then I tried this:
public void deleteSelectedRows() { int[] selected = jTable.getSelectedRows(); int editing = jTable.getEditingRow(); for(int s : selected) { //PS: Is there a better way of doing a linear search? if(s == editing) { return; } } for(int i = selected.length - 1; i >= 0; i--) { model.removeRow(selected[i]); } if(model.getRowCount() < 1) { addEmptyRow(); } }
But that doesn’t delete anything, ever. Judging from println
s I sprinkled around, the last cell to be highlighted (that has the special border seen here on spam
) is considered part of the editing row, and thus triggers my early return
.
So I don’t really care whether the solution involves fixing the original problem–that of the wacky results when a cell being edited is deleted–or this new problem–that of getEditingRow()
not behaving as I expected, it’s just that I need at least one of those to happen. That said, I would be interested to hear both solutions just out of academic curiosity. Thanks in advance.
Advertisement
Answer
Try to include the following lines before removing any rows from your model:
if (table.isEditing()) { table.getCellEditor().stopCellEditing(); }