Hi all, I would lke to implement column sorting in my GUI. I have been investigating how to go about this and am kicking around three different approaches. The first approach is to build a sortTableModel class that extends the table model class. My contractor table model would then extend this class. The second approach is to build a sorting class that sits in between the contractor table model and the JTable. The third approach is to add sorting functionality to the contractor table model class directly. Has anybody got any opinions on this? Do you think it is worth adding column sorting? Thanks, Jonathan
Hi, Here is my approach. My TableModel class implements AbstractTableModel. I have two arrays in my class. The first array stores all the records. The second array has two columns and the same number of rows as the first. The first column is populated by the column which the user wants to sort. The second column is the indices to the first. I use Arrays.sort() to sort the second array. In the getvalue method, this is what I've done.
If the user want to sort another column, I just copy the values of that column with the index to the secondArray and sort it again. If the user clicks the same column the second time, it will sort by descending order. I played at small trick in the Comparator to do by negation. Best Regards.
Joined: Jan 17, 2004
Thanks for the input guys. Frankie I was definitely favouring an approach similar to yours however the one thing that worried me was that it might not be 'OO' enough. This was just because it seemed to mix the contractor table model implementation logic with the logic for sorting tables, rather than having one class with the sorting logic and then extending this class to include the contractor specific logic. Does anyone have any opinions regarding this concern? Is it 6 in one hand and half a dozen in the other or is one definitely a sounder design?
Joined: Dec 25, 2003
I think it is perfectly OO, whichever class has the data has the responsibility to do the job, especially, the sorting can be doing in just one method Arrays.Sort(), if you delegate the sorting logic to another class, you break encapsulation or increased coupling. Best Regards
maybe a bit strong. I mean, you could have the model getting a sorting method from a factory. Then you can concentrate on coding the sort, in the knowledge that you could (at a leter date) add to the available sort methods without changing the model, thereby increasing the level of de-coupling
Anyway, I also think that, for this assignment, it's not necessary to sort the table (just exposes yourself to having marks deducted, IMO!). Thanks, Steve. [ February 02, 2004: Message edited by: Stephen Galbraith ] [ February 02, 2004: Message edited by: Stephen Galbraith ]