1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.argeo.eclipse.ui;
17
18 import org.eclipse.jface.viewers.ColumnViewer;
19 import org.eclipse.jface.viewers.TableViewerColumn;
20 import org.eclipse.jface.viewers.Viewer;
21 import org.eclipse.jface.viewers.ViewerComparator;
22 import org.eclipse.swt.SWT;
23 import org.eclipse.swt.events.SelectionAdapter;
24 import org.eclipse.swt.events.SelectionEvent;
25
26
27 public class ColumnViewerComparator extends ViewerComparator {
28 private static final long serialVersionUID = -2266218906355859909L;
29
30 public static final int ASC = 1;
31
32 public static final int NONE = 0;
33
34 public static final int DESC = -1;
35
36 private int direction = 0;
37
38 private TableViewerColumn column;
39
40 private ColumnViewer viewer;
41
42 public ColumnViewerComparator(TableViewerColumn column) {
43 super(null);
44 this.column = column;
45 this.viewer = column.getViewer();
46 this.column.getColumn().addSelectionListener(new SelectionAdapter() {
47 private static final long serialVersionUID = 7586796298965472189L;
48
49 public void widgetSelected(SelectionEvent e) {
50 if (ColumnViewerComparator.this.viewer.getComparator() != null) {
51 if (ColumnViewerComparator.this.viewer.getComparator() == ColumnViewerComparator.this) {
52 int tdirection = ColumnViewerComparator.this.direction;
53
54 if (tdirection == ASC) {
55 setSortDirection(DESC);
56 } else if (tdirection == DESC) {
57 setSortDirection(NONE);
58 }
59 } else {
60 setSortDirection(ASC);
61 }
62 } else {
63 setSortDirection(ASC);
64 }
65 }
66 });
67 }
68
69 private void setSortDirection(int direction) {
70 if (direction == NONE) {
71 column.getColumn().getParent().setSortColumn(null);
72 column.getColumn().getParent().setSortDirection(SWT.NONE);
73 viewer.setComparator(null);
74 } else {
75 column.getColumn().getParent().setSortColumn(column.getColumn());
76 this.direction = direction;
77
78 if (direction == ASC) {
79 column.getColumn().getParent().setSortDirection(SWT.DOWN);
80 } else {
81 column.getColumn().getParent().setSortDirection(SWT.UP);
82 }
83
84 if (viewer.getComparator() == this) {
85 viewer.refresh();
86 } else {
87 viewer.setComparator(this);
88 }
89
90 }
91 }
92
93 public int compare(Viewer viewer, Object e1, Object e2) {
94 return direction * super.compare(viewer, e1, e2);
95 }
96 }