简体   繁体   中英

JTable remove row by clicking a cell with a custom DeleteCellEditor from the same JTable

In a class called HistoryPanel I have a static JTable called resultsTable with a static DefaultTableModel called tableModel . The table has a custom cell editor:

resultsTable.getColumn("Delete").setCellEditor(new DeleteButtonEditor(new JCheckBox()));

Inside, naturally, I override these two methods like this:

public Object getCellEditorValue()
{
    if (isPushed)
    {
        HistoryPanel.tableModel.removeRow(HistoryPanel.resultsTable.getSelectedRow());
    }
}

protected void fireEditingStopped()
{
    super.fireEditingStopped();
}

The exception is being thrown ONLY when I try to remove the last row of the resultsTable. When I'm removing a row that is not the last one it works perfectly. The exception is:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1 >= 1

And the line of code that causes the exception is:

super.fireEditingStopped();

Can anyone help me? How can I avoid this exception

Currently you remove the row you are editing during the edit operation. It would be a lot easier if you had posted an SSCCE so I could test my proposed solution, but now I will leave that up to you.

I assume that wrapping your

if (isPushed)
{
    HistoryPanel.tableModel.removeRow(HistoryPanel.resultsTable.getSelectedRow());
}

inside an EventQueue.invokeLater call might solve the issue. That way editing is finished when you remove the row.

Really why not use Boolean value directly, why is there Editor for JCheckBox , you have to check tutorial how the JTable works

EDIT

for real TableCellEditor you have to call

int row = table.convertRowIndexToModel(table.getEditingRow());
fireEditingStopped();

and thenafter you can call for delete

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM