Tabelle, sortieren
Folgende Klasse kann eine Tabelle, deren Zeilen auf Beans basieren, sortieren:
public class TableColumnSorter<T> extends ViewerComparator { private String property; private int sortDirection; public TableColumnSorter(String property, int sortDirection) { this.property = property; this.sortDirection = sortDirection; } @Override public int compare(Viewer viewer, Object e1, Object e2) { int result = super.compare(viewer, getColumnValue(e1), getColumnValue(e2)); if (sortDirection == SWT.UP) result *= -1; return result; } @SuppressWarnings("unchecked") public String getColumnValue(Object bean) { T result = null; if (bean != null && property != null) { try{ if (PropertyUtils.isReadable(bean, property)) result = (T) PropertyUtils.getProperty(bean, property); else { String methodName = "get" + ((char) (property.charAt(0)-32)) + property.substring(1); result = (T) MethodUtils.invokeMethod(bean, methodName, bean); } }catch (Exception e){ e.printStackTrace(); } } return result.toString(); } }
Aufruf erfolgt wie folgt:
String propertyName = "nachname"; getTableViewer().setComparator(new TableColumnSorter(propertyName, SWT.DOWN); getTable().setSortColumn(columnIndex); getTable().setSortDirection(SWT.DOWN);