I have a table which contains delete buttons for each row.
I use
int row = table.getEditingRow(); //To fetch the current row to delete.
Then I use
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.removeRow(row);
This deletes a row in JTable when I delete first the first row and anything in between but If I delete the last row it still deletes the last row but then the next item to delete will make an error say if there are 3 items in table
Item1
Item2
Item3
When I delete Item 3
Item1
Item2
When I delete either Item 1 or Item 2 after it will cause an error
java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
No problems when I delete Item1, then Item2, then Item3 or Item2 first, then Item1, then Item3
This is how I constructed my CellEditor
public class JButtonEditor extends AbstractCellEditor implements TableCellEditor, ActionListener{
JTable table;
JButton button = new JButton();
public JButtonEditor(JTable table){
this.table = table;
button.addActionListener(this);
}
@Override
public Object getCellEditorValue() {
return button.getText();
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
button.setText(value.toString());
return button;
}
@Override
public void actionPerformed(ActionEvent e) {
int row = table.getEditingRow();
int column = table.getEditingColumn();
switch(column){
case 3:
manage(groupId); break;
case 4:
editGroup(groupId); break;
case 5:
deleteGroup(groupId,row); break;
}
}
private void deleteGroup(int groupId,int row) {
//do something here to remove the group from the database
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.removeRow(row);
}
I think that after I deleted Item3, when I delete Item1 or Item2 next it thinks that I’m still deleting Item3 and it causes an ArrayOutOfBounds error since Item3 is gone in the tablemodel?
My problem is fixed.
public void actionPerformed(ActionEvent e) {
int row = table.getEditingRow();
int column = table.getEditingColumn();
fireEditingStopped(); //added this
switch(column){
case 3:
manage(groupId); break;
case 4:
editGroup(groupId); break;
case 5:
deleteGroup(groupId,row); break;
}
}
That’s the only thing I changed and I’m still using my Cell Renderer and it now works!
Table Button Column shows how I do this.