HowTo Remove a Row in a JTable with a Custom TableModel

linsek picture linsek · Dec 29, 2010 · Viewed 12.3k times · Source

I've been reading posts similar to mine, and reading through the Java tutorial page but I just can't seem to get this working. I'm not sure if I'm missing something fundamental or not...

I have a custom table model below that I need to be able to delete rows from. The table is initialized empty and rows are added through a combo box and an add button. There is also a delete button that needs to delete the selected row out of the table.

class TableModel extends AbstractTableModel
{
    private String[] columnNames = {"Enabled", "Value" };
    protected Class[] columnClasses = new Class[] { Boolean.class, String.class };

    public int getColumnCount()             { return columnNames.length; }  
    public int getRowCount()                { return filters.size(); }
    public String getColumnName(int col)    { return columnNames[col]; }
    public Class getColumnClass(int col)    { return columnClasses[col]; }

    public Object getValueAt(int row, int col) { ... }

    public void setValueAt(Object value, int row, int col) { ... }

    public void addRow(String value)
    {
        fireTableRowsInserted(filters.size() - 1, filters.size() - 1);
        int row = filters.size() -1 ;
        int col = 1;
        setValueAt(value, row, col);            
    }

    public void removeRow(int row)
    {           
        fireTableRowsDeleted(selectedRow, selectedRow);
    }
}

I have confirmed that selectedRow contains the correct row through prints in the console. The fireTableRowsDeleted function just doesn't do anything. The row still exists. How do you just delete a specific row?

Thanks,

Answer

vickirk picture vickirk · Dec 29, 2010

The call to fireTableRowsDeleted simply fires off the event to indicate rows have been deleted, you still need to actually remove them from the model.