Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparator for a specific column in JTable

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.

like image 948
Eng.Fouad Avatar asked Jan 20 '23 04:01

Eng.Fouad


1 Answers

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.

like image 51
SJuan76 Avatar answered Jan 21 '23 18:01

SJuan76