1
edit
Changes
no edit summary
=== 4. Add Sorting Option ===
4.1Create a new Class <code>StudentViewerComparator.java</code> put it in package <code>sorter</code>:<br/> <pre> package cs.ecl.rcp.simplercp.sorter; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerComparator; import cs.ecl.rcp.simplercp.model.*; public class StudentViewerComparator extends ViewerComparator { private int propertyIndex; private static final int DESCENDING = 1; private int direction = DESCENDING; public StudentViewerComparator() { 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) { Student s1 = (Student) e1; Student s2 = (Student) e2; int rc = 0; switch (propertyIndex) { case 0: rc = s1.getId().compareTo(s2.getId()); break; case 1: rc = s1.getFirstName().compareTo(s2.getFirstName()); break; case 2: rc = s1.getLastName().compareTo(s2.getLastName()); break; case 3: rc = s1.getProgram().compareTo(s2.getProgram()); break; default: rc = 0; } // If descending order, flip the direction if (direction == DESCENDING) { rc = -rc; } return rc; } } </pre><br/>4.2