首先说明一下,对于JFace中的三个主要Viewer,它们的排序功能均来自抽象父类StructuredViewer,在这个抽象类中,有一个变量private ViewerComparator sorter;和两个函数public void setSorter(ViewerSorter sorter)以及public void setComparator(ViewerComparator comparator),来设定viewer的排序类;
通过爬Eclipse的源码我们可以知道ViewerSorter继承自ViewerComparator,而且上述两个函数的实现完全相同,系统推荐使用后者设定排序类;
为了对viewer进行排序,我们需要做以下几件事情。
1、自定义一个类继承自ViewerSorter或者ViewerComparator,然后重载其中的函数public int compare(Viewer viewer, Object e1, Object e2);记住:e1表示需要比较的第一个元素,e2表示第二个元素;如果e1<e2则返回负值,如果e1=e2则返回0,如果e1>e2则返回正值;例如:
public class TableSorter extends ViewerSorter {
private int propertyIndex;
// private static final int ASCENDING = 0;
private static final int DESCENDING = 1;
private int direction = DESCENDING;
public TableSorter() {
this.propertyIndex = 0;
direction = DESCENDING;
}
public void setColumn(int column) {
if (column == this.propertyIndex) {
// Same column as last sort; toggle the direction
direction = 1 - direction;
} else {
// New column; do an ascending sort
this.propertyIndex = column;
direction = DESCENDING;
}
}
@Override
public int compare(Viewer viewer, Object e1, Object e2) {
//将e1和e2转换为模型域的实例;
Person p1 = (Person) e1;
Person p2 = (Person) e2;
int rc = 0;
//根据列的index,比较模型域实例的不同字段;
switch (propertyIndex) {
case 0:
rc = p1.getFirstName().compareTo(p2.getFirstName()); break;
case 1:
rc = p1.getLastName().compareTo(p2.getLastName()); break;
case 2:
rc = p1.getGender().compareTo(p2.getGender()); break;
case 3:
if (p1.isMarried() == p2.isMarried()) {
rc = 0;
} else
rc = (p1.isMarried() ? 1 : -1); break;
default:
rc = 0;
}
// If descending order, flip the direction
if (direction == DESCENDING) {
rc = -rc;
}
return rc;
}
}
2、调用函数setSorter或者setComparator设定viewer的排序类;
3、对于TableViewer来说,定义TableColumn,并为需要排序的TableColumn增加Selection Listener;举例来说如下:
column.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
//这里的index就是从0开始到Table中列数-1为止;
tableSorter.setColumn(index);
int dir = viewer.getTable().getSortDirection();
if (viewer.getTable().getSortColumn() == column) {
dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
} else {
dir = SWT.DOWN;
}
viewer.getTable().setSortDirection(dir);
viewer.getTable().setSortColumn(column);
viewer.refresh();
}
});
这样一来,我们就完成了TableViewer的排序工作;