简体   繁体   中英

HowTo Remove a Row in a JTable with a Custom TableModel

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,

调用fireTableRowsDeleted只会触发事件以指示行已被删除,您实际上仍需要从模型中将其删除。

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

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.

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