4

How can I set a custom comparator for a specific column in JTable?

The third column of my table contains String representaion of double values and I want to creat a comparator for that column so that when I click on the header of that column it will sort according to that comparator.

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • @Eng.Fouad if is there 1) localized Native OS 2) instaled and used proper Font in Native OS 3) correctly set Jave encoding...., then I can't see any problem, really show us your question translated to the code, just my curiosity, if you had problem with that, then why Indian, Chinese or Japan works, or I'm wrong – mKorbel Jul 21 '11 at 21:04

2 Answers2

5

The first question is why, if you are managing doubles, you are dealing with Strings. It should be better if you used the doubles and just set the format in the CellRenderer for that column.

Anyway, what you are looking for may be this: http://download.oracle.com/javase/tutorial/uiswing/examples/components/TableSorterDemoProject/src/components/TableSorter.java


EDIT: If somehow the translation from Double to your representation is complicated, I would create a Comparable class that contains both the Double number and the String representation. Equals(), hashcode() and compareTo() would be implemented using the value of the double; the cellRenderer() and toString() would use the String representation.

SJuan76
  • 24,532
  • 6
  • 47
  • 87
  • I use arabic numbers so that I had to use String – Eng.Fouad Jul 21 '11 at 19:59
  • 1
    +1 This is the preferred approach. Let the renderer handle the view; let the model use `Double`. – trashgod Jul 21 '11 at 20:04
  • @Eng.Fouad, you have the code to pass from a Double to the String representation? – SJuan76 Jul 21 '11 at 20:08
  • @SJuan76 yes. just convert the arabic representation to english representation and then parse it to double – Eng.Fouad Jul 22 '11 at 08:03
  • @Eng.Fouad I meant the other way around (Double --> String). If you have a reasonably fast way to do that conversion, implement it in the cellRenderer. If you can not, look at my edit. – SJuan76 Jul 22 '11 at 09:19
4

In this example, class Value implements Comparable<Value>.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 1
    This approach is useful to effect a particular [natural ordering](http://download.oracle.com/javase/tutorial/collections/interfaces/order.html) that varies from the [default](http://download.oracle.com/javase/tutorial/uiswing/components/table.html#editrender). Note that the implementation of `Comparable` delegates to `Double`. – trashgod Jul 21 '11 at 22:02