platzhirsch platzhirsch - 5 months ago 20
Java Question

Sorting numbers in a JTable

How do I realize sorting of columns containing only numbers in a JTable? There is the class

TableRowSorter
. Using this, however, leads to the following: for every number the string representation is taken by invoking toString and then this is compared instead. What I receive is for instance this:

100, 13, 2, 22, 9
instead 2, 9, 13, 22, 100

TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table);
table.setRowSorter(sorter);


To avoid this, there is the following method:

sorter.setComparator(column,comparator);


Since my numbers are only Integer, Long and Double, I don't see why I should define a humble Comparator of standard java.lang classes. Is there an easier way?

Answer

You should define Number for the column's class.

See TableModel

public Class<?> getColumnClass(int columnIndex);
Comments