Question

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,

Was it helpful?

Solution 2

Immediately after I posted this I figured it out.

The rows contents are based on a List of filters:

public int getRowCount() { return filters.size(); }

My problem was I was trying to delete a row without removing that from the list. So I modified removeRow() to be the following:

public void removeRow(int row)
{
    filters.remove(row);
    fireTableRowsDeleted(row, row);
}

And it works like a charm.

cheers

OTHER TIPS

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.

I think this is the answer:

final int row = selectedRow;
EventQueue.invokeLater(new Runnable() {
       public void run() {
             model.removeRow(row);
       }
});

The row will be deleted when the editing is finished.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top