In swt table- sorting works for Strings how to do sorting for Integer, Double and Date values. And this only works for String ascending. Can anyone suggest a better way to do it.
TableItem item = new TableItem(table, SWT.NONE);
item.setText(new String[] { "1", "v", "1.1", "20/03/2013" });
item = new TableItem(table, SWT.NONE);
item.setText(new String[] { "10", "z", "1.5", "20/04/2013" });
item = new TableItem(table, SWT.NONE);
item.setText(new String[] { "3", "a", "1.3", "30/01/2013" });
Listener sortListener = new Listener() {
public void handleEvent(Event e) {
TableItem[] items = table.getItems();
Collator collator = Collator.getInstance(Locale.getDefault());
TableColumn column = (TableColumn) e.widget;
int index = column == tblclmnNumber ? 0 : 1;
for (int i = 1; i < items.length; i++) {
String value1 = items[i].getText(index);
for (int j = 0; j < i; j++) {
String value2 = items[j].getText(index);
if (collator.compare(value1, value2) < 0) {
String[] values = { items[i].getText(0),
items[i].getText(1), items[i].getText(2),
items[i].getText(3) };
items[i].dispose();
TableItem item = new TableItem(table, SWT.NONE, j);
item.setText(values);
items = table.getItems();
break;
}
}
}
table.setSortColumn(column);
}
};
tblclmnNumber.addListener(SWT.Selection, sortListener);
tblclmnName.addListener(SWT.Selection, sortListener);
tblclmnDeci.addListener(SWT.Selection, sortListener);
tblclmnDate.addListener(SWT.Selection, sortListener);
table.setSortColumn(tblclmnNumber);
table.setSortDirection(SWT.UP);
You can throw a comparator for the column in as data to the column, and then use it to sort. This keeps the sorting logic closer to the definition of the column itself.
I've modified the SWT snippet with sorting to show how is possible to sort columns with with different data types..
Summarize it's totally up to programmer how will be columns in table sorted, because table just always wants array of String for a row whatever they mean..