I have a JTable using AbstractTableModel where I activated the sort with :
table.setAutoCreateRowSorter(true);
I have my own insert and delete functions which were working fine as long as the table is not sorted.
private void insertLine(JTable t)
{
int posInsert = t.getSelectedRow();
Group v = new Group("group", "name","val");
list.add(pos, v);
GroupTableModel model = (GroupTableModel) t.getModel();
model.fireTableRowsInserted(posInsert + 1, posInsert + 1);
}
private void deleteLine(JTable t)
{
int posDel = t.getSelectedRow();
if (posDel != -1)
{
list.remove(pos);
GroupTableModel model = (GroupTableModel) t.getModel();
model.fireTableRowsDeleted(posDel, posDel);
}
}
list is an ArrayList<Group>
which contain the data displayed in the JTable
When the table is sorted, it delete the wrong lines, and insert in the wrong position (not the selected+1). I tried several combinations using convertRowIndexToModel
and convertRowIndexToView
without success. The point is to use the right index when deleting from list, and to have a correct display in view side...
EDIT : After debugging, the issue was with the usage of convertRowIndexToView
. the selectedRow should be used to fire the change not convertRowIndexToView
. Now I have correct content when updating my method like below (same logic for delete) :
private void insertLine(JTable t)
{
int posInsert = t.getSelectedRow();
int modelPosInsert = t.convertRowIndexToModel(posInsert);
Group v = new Group("group", "name","val");
list.add(modelPosInsert, v);
GroupTableModel model = (GroupTableModel) t.getModel();
model.fireTableRowsInserted(posInsert + 1, posInsert + 1);
}
Now the issue is after the change, the sort is partially lost. Only few lines are changed in random positions ?