JTable AutoCreateRowSorter将数字排序为字符串 [英] JTable AutoCreateRowSorter sorting Numbers As Strings

查看:150
本文介绍了JTable AutoCreateRowSorter将数字排序为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JTable:

I have a JTable:

JTable table = new JTable();
String[] colNames = {"c1"};
DefaultTableModel model = new DefaultTableModel();

Integer[] x = new Integer[10];
int[] xi = {0,1,2,3,4,5,6,7,8,9};
for (int i=0; i<10; i++){
    x[i]=new Integer(xi[i]);
}model.addColumn("c1");

table.setModel(model);
table.setEnabled(false);
table.setAutoCreateRowSorter(true);
JScrollPane scrollpane = new JScrollPane(table);
contentPane.add(scrollpane);

现在,当我加载它并单击列标题时,行就好像它们是字符串一样进行排序:

Now when I load this and click on a column title the rows sort as if they were Strings:

0,10 ...(按长度顺序)

0,10... (in order of length)

我该如何更改它以便按数字排序?

How can i change this so they order numerically?

推荐答案

这是因为RowSorter调用TableModel.getColumnClass(int index)来获取与位于index位置的列关联的Class并使用其Comparator来做排序.

This is because the RowSorter calls TableModel.getColumnClass(int index) to get the Class associated to the column in index position and use its Comparator to do the sort.

DefaultTableModelAbstractTableModel的扩展,并且不会覆盖getColumnClass(int columnIndex)方法:

DefaultTableModel extends from AbstractTableModel and doesn't override getColumnClass(int columnIndex) method:

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

如您所见,它总是返回Object.class.为了正确地对列进行排序,您需要覆盖getColumnClass方法.

As you can see it always return Object.class. To properly sort your column, you need to override getColumnClass method.

这篇关于JTable AutoCreateRowSorter将数字排序为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆