JTable AutoCreateRowSorter sorting Numbers As Strings

ⅰ亾dé卋堺 提交于 2019-12-13 17:01:56

问题


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... (in order of length)

How can i change this so they order numerically?


回答1:


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.

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

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

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




回答2:


How can i change this so they order numerically?

Override the getColumnClass() method of your TableModel to return Integer.class and the Integer Comparator will be used to sort the data instead of the String comparator.



来源:https://stackoverflow.com/questions/19525484/jtable-autocreaterowsorter-sorting-numbers-as-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!