Preserve JTable selection across TableModel change

前端 未结 7 1613
北荒
北荒 2021-02-07 11:52

We\'re seeing JTable selection get cleared when we do a fireTableDataChanged() or fireTableRowsUpdated() from the TableModel.

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-07 12:35

    You can automatically preserve a table's selection if the STRUCTURE of that table hasn't changed (i.e. if you haven't add/removed any columns/rows) as follows.

    If you've written your own implementation of TableModel, you can simply override the fireTableDataChanged() method:

    @Override
    public void fireTableDataChanged() {
        fireTableChanged(new TableModelEvent(this, //tableModel
            0, //firstRow
            getRowCount() - 1, //lastRow 
            TableModelEvent.ALL_COLUMNS, //column 
            TableModelEvent.UPDATE)); //changeType
    }
    

    and this should ensure that your selection is maintained provided that only the data and not the structure of the table has changed. The only difference between this, and what would be called if this method weren't overridden is that getRowCount() - 1 is passed for the lastRow argument instead of Integer.MAX_VALUE, the latter of which acts a signifier that not only has all the data in the table changed but that the number of rows may have as well.

提交回复
热议问题