source: trunk/src/org/expeditee/agents/Sort.java@ 185

Last change on this file since 185 was 185, checked in by ra33, 16 years ago
File size: 1.6 KB
Line 
1package org.expeditee.agents;
2
3import java.awt.Point;
4import java.util.ArrayList;
5import java.util.Collection;
6import java.util.Collections;
7import java.util.Comparator;
8
9import org.expeditee.gui.Frame;
10import org.expeditee.gui.FrameGraphics;
11import org.expeditee.gui.FrameUtils;
12import org.expeditee.items.Text;
13
14public class Sort extends DefaultAgent {
15
16 /**
17 * Sorts all the text Items on the given Frame alphabetically. The Items are
18 * then rearranged to reflect this ordering.
19 */
20 public Frame process(Frame start) {
21 // Check the position of the cursor and only format stuff inside the
22 // same box as the cursor
23 Collection<Text> itemsToSort = FrameUtils.getCurrentTextItems();
24 if (itemsToSort.size() < 1) {
25 itemsToSort = start.getBodyTextItems(false);
26 }
27
28 ArrayList<Text> textItems = new ArrayList<Text>();
29 textItems.addAll(itemsToSort);
30
31 // copy current positions of items
32 ArrayList<Point> positions = new ArrayList<Point>(textItems.size());
33
34 for (int i = 0; i < textItems.size(); i++)
35 positions.add(i, textItems.get(i).getPosition());
36
37 // Sort text items by their strings
38 Collections.sort(textItems, new Comparator<Text>() {
39 public int compare(Text a, Text b) {
40 return String.CASE_INSENSITIVE_ORDER.compare(a.getText(), b
41 .getText());
42 }
43 });
44
45 // update positions based on new order
46 for (int i = 0; i < positions.size(); i++)
47 textItems.get(i)
48 .setPosition(positions.get(i).x, positions.get(i).y);
49
50 // items will need to be resorted after this
51 start.setResort(true);
52 FrameGraphics.Repaint();
53
54 return null;
55 }
56
57 @Override
58 protected void finalise(Frame start) {
59 message("Sorting Complete.");
60 }
61}
Note: See TracBrowser for help on using the repository browser.