Search code examples
javaswingjtabletablerowsorter

How can I sort a table by displayed value rather than internal value?


I am using ETable for a little bit of added functionality over the standard JTable.

The problem I am facing is in sorting the table correctly when the column headers are clicked. Currently, I have a date field displaying the Modified Julian Date (MJD) in its raw (double) format. Internally, it is an MJD object (which looks like a date string). When the table is sorted, the column treated in the default manner (lexicographical sort) and thus yields a list like 1.0, 10.0, 100.0, 101.0, .... If I display the MJD object rather than the double form, it is sorted correctly; however, I need to display it as a double. How can I force the comparisons and sorting to be done based on what is displayed?

Note that I have looked at several similar questions posted here like Java JTable Sorting Doesn't Work for Just One Column. This type of solution doesn't work for me since I cannot simply return a double class for the column since it is internally a different object type.


Solution

  • As illustrated in the JTable tutorial, you can set a TableRowSorter on your table or on that specific column. The DefaultRowSorter#setComparator is interesting in your case: you can re-use the default row sorter for all your columns, and just specify a custom Comparator for that specific column.

    Of course, if your objects in the table model already implement Comparable, there is no need to set your own Comparator. Just make sure that the TableModel#getColumnClass returns the correct class.