views:

959

answers:

2

Here's the thing: a sortable JTable backed by JTableModel with an array of objects that populate rows (one object = one row). Need to delete rows.

Without sorting, deleting an object is simple: get selected row index, delete array object under the same index. With sorting, though, row indexes mess up in a sense that they no longer match backing array object indexes. What's the proper way to overcome this?

+2  A: 

I think ( not quite sure ) there is a method like "modelToView" which returns the actual index in the model a view index represents.

So, for instance you have A,B,C,D and then you sort desc. D,C,B,A this method would return 0 for view index 3 ( A )

I think this was on JXTable which supports sorting or in JTable in Java 6.

If you have build this sorting your self, consider adding this method.

OscarRyz
+5  A: 

Oscar was almost right, here's how it should be done:

int selectedRow = table.getSelectedRow();
tableModel.removeRow(table.convertRowIndexToModel(selectedRow));
alex
Ahh that one!! :) I didn't quite remember the exact API, but I hope that gave you something to search into. Also, there is the opposite method convertRowModelToIndex ( or something like that )
OscarRyz
Yeah, that very one :). And shame on me, it's mentioned here: http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#sorting
alex
he he he... yeap... sometimes we do need a mind-reading pop up that says "Are you looking for convertRowIndextToModel in this page? Scroll down, it's there... "
OscarRyz