Thursday, September 20, 2007

Today I struggled with sorting columns in a JTable in Java 1.6. I wanted to have an underlying object (called job) which corresponded with a table Row. At first I created my own JobTableModel which implemented AbstractTableModel. This worked great until I tried to use table sorters. The underlying ArrayList containing my Job objects were synced up with the the row that represented them, so when you sorted the rows got jumbled compared to their corresponding job objects.

To solve this problem I decided to just keep my list of job objects unsorted, and just search the list based on a value in the table which would match one of the variables in the job object. This worked great until I sorted a column; which utterly confused me. Apparently, when you use JTable.getSelectedRow it still doesn't match up with the underlying table model. Instead you have to make this call to get the actual row that was clicked!
int selected=_tJobs.convertRowIndexToMode(_tJobs.getSelectedRow());

Phew, now everything works great! Thank you Java for adding RowSorting with JTables!

Buy Prints

  © Blogger template 'Photoblog II' by Ourblogtemplates.com 2008

Back to TOP