Sorting numbers in a JTable
How do I realize sorting of columns containing only numbers in a JTable? The开发者_运维百科re 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?
You should define Number for the column's class.
See TableModel
public Class<?> getColumnClass(int columnIndex);
How is your table model defined? If the getColumnClass
method return Integer.class
(or Long.class
, or Number.class
, depending on what the column contains), then the sort should be right, and you shouldn't have to configure any specific row sorter.
精彩评论