抽象类StructuredViewer
在这个抽象类中,两个函数public void setSorter(ViewerSorter sorter)以及public void setComparator(ViewerComparator comparator),来设定viewer的排序类;
ViewerSorter继承自ViewerComparator,但从Eclipse3.3开始被后者替代。
TableView间接继承StructuredViewer,通过setComparator(ViewerComparator comparator)排序
为了对TableView进行排序,我们需要做以下几件事情。
1、自定义一个类继承自ViewerComparator,然后重载其中的函数public int compare(Viewer viewer, Object e1, Object e2);记住:e1表示需要比较的第一个元素,e2表示第二个元素;如果e1<e2则返回负值,如果e1=e2则返回0,如果e1>e2则返回正值;例如:
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.SWT;
import de.vogella.jface.tableviewer.model.Person;
public class MyViewerComparator extends ViewerComparator {
private int propertyIndex;
private static final int DESCENDING = 1;
private int direction = DESCENDING;
public MyViewerComparator() {
this.propertyIndex = 0;
direction = DESCENDING;
}
public int getDirection() {
return direction == 1 ? SWT.DOWN : SWT.UP;
}
public void setColumn(int column) {
//同一列第二次以后排序需切换排序方式
if (column == this.propertyIndex) {
// 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) {
Person p1 = (Person) e1;
Person p2 = (Person) e2;
int rc = 0;
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、调用函数setComparator设定TableViewer的排序类;
3、对于TableViewer来说,定义TableColumn,并为需要排序的TableColumn增加Selection Listener;举例来说如下:
private TableViewerColumn createTableViewerColumn(String title, int bound,
final int colNumber) {
final TableViewerColumn viewerColumn = new TableViewerColumn(viewer,
SWT.NONE);
final TableColumn column = viewerColumn.getColumn();
column.setText(title);
column.setWidth(bound);
column.setResizable(true);
column.setMoveable(true);
//TableColumn增加Selection Listener
column.addSelectionListener(getSelectionAdapter(column, colNumber));
return viewerColumn;
}
private SelectionAdapter getSelectionAdapter(final TableColumn column,
final int index) {
SelectionAdapter selectionAdapter = new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
comparator.setColumn(index);
int dir = comparator.getDirection();
viewer.getTable().setSortDirection(dir);
viewer.getTable().setSortColumn(column);
viewer.refresh();
}
};
return selectionAdapter;
}
这样一来,我们就完成了TableViewer的排序工作;
参考:http://www.vogella.de/articles/EclipseJFaceTableAdvanced/article.html