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?
This is because the
RowSortercallsTableModel.getColumnClass(int index)to get theClassassociated to the column inindexposition and use itsComparatorto do the sort.DefaultTableModelextends fromAbstractTableModeland doesn't overridegetColumnClass(int columnIndex)method:As you can see it always return
Object.class. To properly sort your column, you need to overridegetColumnClassmethod.