[英]Sorting numbers in a JTable
如何实现对 JTable 中仅包含数字的列进行排序? 有 class TableRowSorter
。 但是,使用它会导致以下结果:对于每个数字,通过调用 toString 来获取字符串表示,然后进行比较。 我收到的是例如:
100, 13, 2, 22, 9 而不是 2, 9, 13, 22, 100
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table);
table.setRowSorter(sorter);
为了避免这种情况,有以下方法:
sorter.setComparator(column,comparator);
由于我的数字只有 Integer、Long 和 Double,我不明白为什么要定义标准 java.lang 类的不起眼的 Comparator 。 有没有更简单的方法?
您应该为列的 class 定义 Number。
见表模型
public Class<?> getColumnClass(int columnIndex);
您的表 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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.