ViewerSorter problem with a Table [message #466066] |
Fri, 30 December 2005 10:42  |
Eclipse User |
|
|
|
Hi all.
I would like to make my SWT-Table sortable. Therefore I implemented a
ViewerSorter on my table. Now to my problem: If I select a column to sort,
the sorting only orients to the first column (whatever which table I
selected to sort), but I want that the table should be sorted for the
selected column.
With the following Code, I set a listener to my columns in the table:
column1 = new TableColumn(table, SWT.NONE);
column1.setText("Modul");
column1.setWidth(200);
column1.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
((NameSorter)tableViewer.getSorter()).setCriteria(NameSorter .MODUL);
tableViewer.refresh();
}
});
This is my ViewerSorter class:
public class NameSorter extends ViewerSorter
{
// columns
public final static int MODUL = 0;
public final static int LABEL = 1;
// Criteria for NameSorter instance
private int criteria;
private boolean toggleFlag = true;
public NameSorter(int criteria)
{
super();
this.criteria = criteria;
}
public void setCriteria(int criteria)
{
if (this.criteria != criteria)
{
this.criteria = criteria;
} else
{
toggleFlag = !toggleFlag;
}
}
public void sort(final Viewer viewer, Object[] elements)
{
Arrays.sort(elements);
}
}
Can somebody help me?
Sebastian
|
|
|
Re: ViewerSorter problem with a Table [message #466081 is a reply to message #466066] |
Fri, 30 December 2005 17:00   |
Eclipse User |
|
|
|
I'm going to assume that your criteria is the same as the column header.
So let's say your object are player objects and there's 4 columns in your
table: name, last name, points, rebounds and assists. in your sorter
class, don't override the sort method, override the compare method. Here
is an example:
//assume that in the constructor you passed the index number of the
//column that you want to sort, in a variable called column
public int compare(Viewer viewer, Object e1, Object e2) {
int returnValue = 0;
if (e1 instanceof Player) {
Player p1 = (Player) e1;
Player p2 = (Player) e2;
// Determine which column and do the appropriate sort
switch (column) {
case PlayerConst.COLUMN_FIRST_NAME:
returnValue = collator.compare(p1.getFirstName(), p2.getFirstName());
break;
case PlayerConst.COLUMN_LAST_NAME:
returnValue = collator.compare(p1.getLastName(),
p2.getLastName());
break;
case PlayerConst.COLUMN_POINTS:
returnValue = p1.getPoints() > p2.getPoints() ? 1 : -1;
break;
case PlayerConst.COLUMN_REBOUNDS:
returnValue = p1.getRebounds() > p2.getRebounds() ? 1 : -1;
break;
case PlayerConst.COLUMN_ASSISTS:
returnValue = p1.getAssists() > p2.getAssists() ? 1 : -1;
break;
}
// If descending order, flip the direction
// introduce some kind of if statement and
// check sort direction, then you can say
// returnValue = -returnValue;
return returnValue;
}
}
|
|
|
|
|
|
|
Powered by
FUDForum. Page generated in 0.07755 seconds