简体   繁体   English

JTable 中的数字排序

[英]Sorting numbers in a JTable

How do I realize sorting of columns containing only numbers in a JTable?如何实现对 JTable 中仅包含数字的列进行排序? There is the class TableRowSorter .有 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.但是,使用它会导致以下结果:对于每个数字,通过调用 toString 来获取字符串表示,然后进行比较。 What I receive is for instance this:我收到的是例如:

100, 13, 2, 22, 9 instead 2, 9, 13, 22, 100 100, 13, 2, 22, 9 而不是 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.由于我的数字只有 Integer、Long 和 Double,我不明白为什么要定义标准 java.lang 类的不起眼的 Comparator 。 Is there an easier way?有没有更简单的方法?

You should define Number for the column's class.您应该为列的 class 定义 Number。

See TableModel见表模型

public Class<?> getColumnClass(int columnIndex);

How is your table model defined?您的表 model 是如何定义的? 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. 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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