简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM