CODEXE

Add sorter to common navigator

For sorting the elements in the common navigator, we need org.eclipse.jface.viewers.ViewerSorter.

1. Add common sorter to your navigator content. Set the class name and id to customplugin.sorters.NavigatorSorter. Add an instance(customplugin.views.navigator.data.PropertiesTreeData) to the common sorter which means that the sorter will act on the specific instance.

navigator sorter

Please remember to add the navigator content to the viewer content binding.

bind navigator content

2. Implement compare method in the sorter. The sorter will extract the numbers in the name. And the element with the biggest number will have a higher ranking.

public class NavigatorSorter extends ViewerSorter {

	public NavigatorSorter() {
		// TODO Auto-generated constructor stub
	}

	public NavigatorSorter(Collator collator) {
		super(collator);
		// TODO Auto-generated constructor stub
	}
	@Override
	public int compare(Viewer viewer, Object e1, Object e2){
		int result = -1;
		if(e1 instanceof PropertiesTreeData && e2 instanceof PropertiesTreeData){
			PropertiesTreeData p1 = (PropertiesTreeData) e1;
			PropertiesTreeData p2 = (PropertiesTreeData) e2;
			int numInP1 = Integer.parseInt(p1.getName().replaceAll("[\\D]", ""));
			int numInP2 = Integer.parseInt(p2.getName().replaceAll("[\\D]", ""));
			
			result = numInP1 < numInP2? 1 : -1;
		}
		return result;
	}
}
			 

3. Result

Before adding sorter.

navigator sorter

After adding sorter.

navigator sorter