开发者

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,


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜