I have found quite a few questions related to this but I haven't found a simple solution to my issue though.
I can't find a way to make my JTable sort Double values properly.
I extended AbstractTableModel to receive a Class array and return the proper types per column:
class TableModelMod extends AbstractTableModel{
private ArrayList data;
private String [] headers;
private Class [] types;
TableModelMod(String [] heads, ArrayList datas, Class [] classes){
headers = heads;
data = datas;
types = classes;
}
...
@Override public Class getColumnClass(int c){
if (c > types.length - 1)
return null;
else
return types[c];
}
...
And then in my custom JTable constructor:
TableRowSorter<TableModelMod> sorter = new TableRowSorter<TableModelMod>((TableModelMod)getModel());
But then I get this error when adding rows:
java.lang.IllegalArgumentException: Cannot format given Object as a Number
It fails at method DecimalFormat.format(Object number, StringBuffer toAppendTo, FieldPosition pos)
that accepts most numeric types but Double.
If I use another class for the Double columns I get no error but still the sorting does not work as expected. I tried with different numeric classes but none seem to sort doubles correctly:
@Override public Class getColumnClass(int c){
if (c > types.length - 1)
return null;
else if (types[c] == Double.class)
return Number.class;
else
return types[c];
}
I'm not sure if I what I need is to implement a custom RowSorter, a custom CellRenderer, or both.
Could someone guide me on how to fix this the simpler way?
Thanks a lot and best regards.
EDITED: SOLVED
It's quite embarrassing to tell where the problem was.
The ArrayList containing the Object[] rows was filled from a database ResultSet using getString(int) instead of getObject(int) or getDouble(int), therefore the value could not be used as Double by the renderer. It's weird that it didn't give exceptions using Integer or Number as column class, but it was being sorted as a String anyways. I was looking for an issue in the wrong classes since I was convinced my ArrayList contained just Objects.
Thanks a lot for your examples, looking at them I noticed my doubles were actually Strings and then I could find where the conversion was happening.