我使用Vogella教程在插件视图中创建了一个tableviewer并对列进行排序。 问题是目前的排序是基于一列完成的。如果第一个名字是相同的,我想按字母顺序对姓氏进行排序:
实施例
Unsorted :
Col 1 Col 2
John Smith
John A
Sorted:
Col1 Col2
John A
John Smith
使用过的代码:
package de.vogella.jface.tableviewer.sorter;
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) {
// 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) {
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;
}
}
我知道compareTo在比较元素相等时返回0,但我不知道如何保持一列的比较,并根据第一列排序比较第二列元素。
答案 0 :(得分:1)
尝试以下方法:
public int compare(Viewer viewer, Object e1, Object e2) {
Person p1 = (Person) e1;
Person p2 = (Person) e2;
int rc = 0;
if(!p1.getFirstName().equals(p2.getFirstName())) {
rc = p1.getFirstName().compareTo(p2.getFirstName());
}else if(!p1.getLastName().equals(p2.getLastName())) {
rc = p1.getLastName().compareTo(p2.getLastName());
}else if(!p1.getGender().equals(p2.getGender())) {
rc = p1.getGender().compareTo(p2.getGender());
}else if(!p1.isMArried==p2.isMarried) {
rc = (p1.isMarried() ? 1 : -1);
}else rc=0;
return rc;
}