![](/img/trans.png)
[英]TableModel RemoveRow() removing wrong row if JTable is sorted
[英]JTable removeRow(), removing wrong row
我有一個JTable,我需要刪除一行,即選定的行。
所以首先,我得到表模型:
DefaultTableModel model = (DefaultTableModel) table.getModel();
然后是選定的行(如果選擇了第二行,則返回1,這是可以理解的,因為行從零開始):
int selectedRow = table.getSelectedRow();
然后,我嘗試刪除該行:
model.removeRow(selectedRow);
然后我再次設置表模型:
table.setModel(model);
這實現的是刪除完全隨機的行。 我根本不明白為什么。 我已經使用table.setRowSorter(sorter)對表進行了排序,但是我不知道為什么這應該是一個問題。 如果絕對需要SSCCE,請告訴我,因為在生產一個SSCCE之前,我需要修改很多代碼。
注意:這兩行返回的值不同:
System.out.println(table.getValueAt(selectedRow, 1));
System.out.println(model.getValueAt(selectedRow, 1));
如果JTable
過濾或排序,則可以轉換
int modelRow = convertRowIndexToModel(row);
JTable.getSelectedRow
返回的索引是一個view
索引:它是最終用戶在表中看到的行的索引。 它與模型索引不同,因為如果對表進行排序,則模型中的索引不會更改,但是視圖中的索引會更改。 因此,您必須始終使用JTable.convertRowIndexToModel
從視圖索引獲取模型索引。
請注意,必須對列進行相同的操作,因為用戶可能會選擇根據其喜好對列進行重新排序。
另外,您不必在每次刪除行時都再次設置模型。 取而代之的是,您的模型應觸發TableModelEvent來通知視圖有關移除的信息。 參見AbstractTableModel.fireTableRowsDeleted
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.