Fred Trellis Fred Trellis - 1 month ago 10
Java Question

SWT Snippet2. Table sorting. items array changes in the loop. How does this work?


http://git.eclipse.org/c/platform/eclipse.platform.swt.git/tree/examples/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet2.java


I am trying in SWT to add sorting to a table widget. Copying the code from Snippet2
sortListener
Handler doesn't work. It correctly swaps two items into sorted order. More than 2 items in the table, and the results are unpredictable.

It seems to me (in the following code extract from Snippet2
sortListener
) that
items[i].dispose()
is going to change the array of
TableItems
called items that we are iterating over in the outer for loop,
for (int i = 1 ......
Also, when one item is
disposed()
, and inserted into items at a new index, the whole array is recreated afresh. That surely breaks the iteration?

So, I guess I have two questions:


  1. What am I not understanding about Snippet2's algorithm?

  2. Is there any other obvious reason why a sort operation might return random results (bearing in mind I am a noob, so am likely to have made the stupidest of mistakes)?



Here is my code:

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 == column1 ? 0 : 1;
for (int i = 1; i < items.length; i++) { <--------- HERE
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].dispose(); <--------- HERE
TableItem item = new TableItem(table, SWT.NONE, j);
item.setText(values);
items = table.getItems(); <--------- HERE

break;
}
}
}
table.setSortColumn(column);
}
};

Answer

You may want to use JFace wrapper for SWT table (org.eclipse.jface.viewers.TableViewer), which gives your table more built in features. I suggest this tutorial for JFace TableViewer. Here is tutorial for sorting TableViewer.

Comments