]> git.argeo.org Git - lgpl/argeo-commons.git/blob - ColumnViewerComparator.java
dd7df8d305a4648b726ae566c89d288eb93dc691
[lgpl/argeo-commons.git] / ColumnViewerComparator.java
1 package org.argeo.eclipse.ui;
2
3 import java.util.Comparator;
4
5 import org.eclipse.jface.viewers.ColumnViewer;
6 import org.eclipse.jface.viewers.TableViewerColumn;
7 import org.eclipse.jface.viewers.Viewer;
8 import org.eclipse.jface.viewers.ViewerComparator;
9 import org.eclipse.swt.SWT;
10 import org.eclipse.swt.events.SelectionAdapter;
11 import org.eclipse.swt.events.SelectionEvent;
12
13 /** Generic column viewer sortter */
14 public class ColumnViewerComparator<T> extends ViewerComparator {
15 public static final int ASC = 1;
16
17 public static final int NONE = 0;
18
19 public static final int DESC = -1;
20
21 private int direction = 0;
22
23 private TableViewerColumn column;
24
25 private ColumnViewer viewer;
26
27 public ColumnViewerComparator(TableViewerColumn column,
28 Comparator<T> comparator) {
29 super(comparator);
30 this.column = column;
31 this.viewer = column.getViewer();
32 this.column.getColumn().addSelectionListener(new SelectionAdapter() {
33
34 public void widgetSelected(SelectionEvent e) {
35 if (ColumnViewerComparator.this.viewer.getComparator() != null) {
36 if (ColumnViewerComparator.this.viewer.getComparator() == ColumnViewerComparator.this) {
37 int tdirection = ColumnViewerComparator.this.direction;
38
39 if (tdirection == ASC) {
40 setSortDirection(DESC);
41 } else if (tdirection == DESC) {
42 setSortDirection(NONE);
43 }
44 } else {
45 setSortDirection(ASC);
46 }
47 } else {
48 setSortDirection(ASC);
49 }
50 }
51 });
52 }
53
54 private void setSortDirection(int direction) {
55 if (direction == NONE) {
56 column.getColumn().getParent().setSortColumn(null);
57 column.getColumn().getParent().setSortDirection(SWT.NONE);
58 viewer.setComparator(null);
59 } else {
60 column.getColumn().getParent().setSortColumn(column.getColumn());
61 this.direction = direction;
62
63 if (direction == ASC) {
64 column.getColumn().getParent().setSortDirection(SWT.DOWN);
65 } else {
66 column.getColumn().getParent().setSortDirection(SWT.UP);
67 }
68
69 if (viewer.getComparator() == this) {
70 viewer.refresh();
71 } else {
72 viewer.setComparator(this);
73 }
74
75 }
76 }
77
78 @SuppressWarnings("unchecked")
79 public int compare(Viewer viewer, Object e1, Object e2) {
80 return direction * getComparator().compare((T) e1, (T) e2);
81 }
82 }