简体   繁体   中英

Sorting Number in a JTable issue

How do I realize sorting of columns containing. I set Cloumnclass is Number.Class

public Class<?> getColumnClass(int columnIndex) {
return Number.class;
}

and Create TableRowSorter

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

The result 8, 80, 9, 989 instead 989 , 80, 9, 8

From the documentation of TableRowSorter :

TableRowSorter uses Comparator s for doing comparisons. The following defines how a Comparator is chosen for a column:

  1. If a Comparator has been specified for the column by the setComparator method, use it.
  2. If the column class as returned by getColumnClass is String , use the Comparator returned by Collator.getInstance() .
  3. If the column class implements Comparable , use a Comparator that invokes the compareTo method.
  4. If a TableStringConverter has been specified, use it to convert the values to String s and then use the Comparator returned by Collator.getInstance() .
  5. Otherwise use the Comparator returned by Collator.getInstance() on the results from calling toString on the objects.

The third and fifth rule are the cause of your issue: You are returning Number.class , which does not implement Comparable. Therefore, your table is sorting using the fifth rule: your values are being treated as Strings.

Instead of returning Number.class, you need to return something which actually implements Comparable, such as Integer.class, Double.class, or BigDecimal.class. The javadoc of each class will tell you what interfaces it implements.

Alternatively, you could install a custom Comparator on the table column, but your Comparator will have to do the work of casting the values and possibly converting them. Returning a Comparable class is much easier.

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