简体   繁体   English

如何使用自定义TableModel删除JTable中的行

[英]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. 我一直在阅读与我的文章相似的文章,并阅读Java教程页面,但似乎无法正常工作。 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. 我已确认selectedRow在控制台中的打印中包含正确的行。 The fireTableRowsDeleted function just doesn't do anything. fireTableRowsDeleted函数只是不执行任何操作。 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: 因此,我将removeRow()修改为以下内容:

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. 编辑完成后,该行将被删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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