In fact, it's more an answer than a question. I have had an issue with TableRowSorter when creating JTable from file. I use TableModel like this:
public class TModel extends AbstractTableModel {
public Vector data;
public Vector colNames;
public String datafile;
Class[] types = {Integer.class, Date.class, Number.class, String.class, Character.class};
public TModel(String f) {
datafile = f;
initVectors();
}
public void initVectors() {
String aLine;
data = new Vector();
colNames = new Vector();
try {
FileInputStream fin = new FileInputStream(datafile);
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
// extract column names
StringTokenizer st1 =
new StringTokenizer(br.readLine(), "|");
while (st1.hasMoreTokens())
colNames.addElement(st1.nextToken());
// extract data
while ((aLine = br.readLine()) != null) {
StringTokenizer st2 =
new StringTokenizer(aLine, "|");
while (st2.hasMoreTokens())
data.addElement(st2.nextToken());
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public int getRowCount() {
return data.size() / getColumnCount();
}
public int getColumnCount() {
return colNames.size();
}
public String getColumnName(int columnIndex) {
String colName = "";
if (columnIndex <= getColumnCount())
colName = (String) colNames.elementAt(columnIndex);
return colName;
}
public Class getColumnClass(int columnIndex) {
return this.types[columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
public Object getValueAt(int rowIndex, int columnIndex) {
return data.elementAt((rowIndex * getColumnCount()) + columnIndex);
}
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
return;
}
The issue was that first column in table sorted like String regardless which type it returns from "GetColumnClass" method. Most popular recommendations for such problem are: "You should override your GetColumnClass method" or "Set specific type for each column".. Sadly, none of that works for me :_( This topic helped me a lot, mostly snippet from Alanmars. Simple soution: if TableRowSorter treats numbers like String, just make it compare them like Integer! Below - snippet, that works for me:
TModel tModel = new TModel(selectedFile);
JTable table = new JTable();
JScrollPane scrollPane = new JScrollPane(table, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
sorter = new TableRowSorter<>(tModel);
sorter.setComparator(IndexOfDesiredColumn, new Comparator<String>() {
@Override
public int compare(String n1, String n2) {
return Integer.parseInt(n1) - Integer.parseInt(n2);
}
});
table.setModel(tModel);
table.setRowSorter(sorter);
Hope this tread will save time for those who'll face same problem as me.