开发者

JTable removeRow(), removing wrong row

开发者 https://www.devze.com 2023-04-09 18:01 出处:网络
I have a JTable and I need to remove a row, namely, the selected row. So first, I get the the table model :

I have a JTable and I need to remove a row, namely, the selected row.

So first, I get the the table model :

    DefaultTableModel model = (DefaultTableModel) table.getModel();

Then the selected row (if the second row is selected, this returns 1, which is understandable because rows start from zero):

    int selectedRow = table.getSelectedRow();

Then I try to remove the row:

    model.removeRow(selectedRow);

Then I set the table model again:

    table.setModel(model);

What this achieves is removing a completely random row. I simply can't understand why. I have sorted the table at some point, using table.setRowSorter(sorter), but I don't know why that should be a problem. If an SSCCE is absolutely ne开发者_运维知识库eded please let me know, because I have a lot of code to modify before I can produce one.

NOTE: The values returned by these two lines differ:

    System.out.println(table.getValueAt(selectedRow, 1));
    System.out.println(model.getValueAt(selectedRow, 1));


If is JTable filtered or sorted then you can convert

int modelRow = convertRowIndexToModel(row);


The index returned by JTable.getSelectedRow is a view index : it's the index of the row as seen by the end-user in the table. It's not the same as the model index, because if you sort the table, the indices in the model don't change, but the indices in the view do change. So, you must always use JTable.convertRowIndexToModel to get the model index from the view index.

Note that the same must be done for columns, because the user might choose to reorder columns to its taste.

Also, you shouldn't have to set the model again each time you remove a row. Instead, your model should fire a TableModelEvent to inform the view about the removal. See AbstractTableModel.fireTableRowsDeleted.

0

精彩评论

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

关注公众号