1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package net.wotonomy.ui.swing.util;
20
21 import java.awt.Component;
22 import java.awt.Container;
23 import java.awt.Point;
24 import java.io.Serializable;
25 import java.util.Comparator;
26
27 import javax.swing.SwingUtilities;
28
29 /***
30 * A Comparator that will sort components in a common container
31 * based first on their y-coordinate and then on their x-coordinate,
32 * producing a list sorted from top to bottom and left to right.
33 * If all components are not in the same container, the resulting
34 * sort is undefined.
35 *
36 * @author michael@mpowers.net
37 * @author $Author: cgruber $
38 * @version $Revision: 904 $
39 */
40 public class PositionComparator implements Comparator, Serializable
41 {
42 private Container rootContainer;
43 private transient Component c1, c2;
44 private transient Point p1, p2;
45
46 /***
47 * Standard constructor to configure the comparator.
48 * @param aContainer The common container for all the objects to be compared.
49 */
50 public PositionComparator( Container aContainer )
51 {
52 rootContainer = aContainer;
53 }
54
55
56
57 public int compare(Object o1, Object o2)
58 {
59 c1 = (Component) o1;
60 c2 = (Component) o2;
61
62 p1 = SwingUtilities.convertPoint( c1.getParent(), c1.getLocation(), rootContainer );
63 p2 = SwingUtilities.convertPoint( c2.getParent(), c2.getLocation(), rootContainer );
64
65 if ( p1.y != p2.y )
66 {
67 return p1.y - p2.y;
68 }
69 return p1.x - p2.x;
70 }
71 }
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89