1 package nl.tudelft.goal.ut2004.visualizer.gui.widgets;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.LinkedList;
6 import java.util.List;
7 import java.util.TreeMap;
8
9 import javax.swing.ComboBoxModel;
10 import javax.swing.event.ListDataEvent;
11 import javax.swing.event.ListDataListener;
12
13 public final class SuggestionModel implements ComboBoxModel {
14
15 private final TreeMap<String, Object> map;
16 private final List<String> sortedKeys;
17
18 public SuggestionModel() {
19 this.map = new TreeMap<String, Object>();
20 this.sortedKeys = new ArrayList<String>();
21 this.listeners = new LinkedList<ListDataListener>();
22 }
23
24 public void addElement(Object element) {
25 map.put(element.toString(), element);
26 sortedKeys.add(element.toString());
27
28 Collections.sort(sortedKeys);
29 modelChanged();
30 }
31
32 private void modelChanged() {
33 setSelectedItem(selected);
34 notifyListeners();
35 }
36
37 public void removeElement(Object element) {
38 map.remove(element.toString());
39 sortedKeys.remove(element.toString());
40 Collections.sort(sortedKeys);
41 modelChanged();
42 }
43
44 private void notifyListeners() {
45 for (ListDataListener l : listeners) {
46 l.contentsChanged(new ListDataEvent(this,
47 ListDataEvent.CONTENTS_CHANGED, 0, getSize()));
48 }
49 }
50
51 public List<String> sugestFor(String query) {
52
53 String lowerCaseQuery = query.toLowerCase();
54
55
56 List<String> suggestion = new LinkedList<String>();
57 for (String key : map.keySet()) {
58 if (key.toLowerCase().contains(lowerCaseQuery)) {
59 System.out.println("Found " + key);
60 suggestion.add(key);
61 }
62 }
63
64 sortedKeys.clear();
65 sortedKeys.addAll(suggestion);
66
67
68
69
70
71 return suggestion;
72 }
73
74 @Override
75 public Object getElementAt(int index) {
76 return map.get(sortedKeys.get(index));
77 }
78
79 @Override
80 public int getSize() {
81 return sortedKeys.size();
82 }
83
84 private final List<ListDataListener> listeners;
85
86 @Override
87 public void removeListDataListener(ListDataListener l) {
88 listeners.remove(l);
89 }
90
91 @Override
92 public void addListDataListener(ListDataListener l) {
93 listeners.add(l);
94 }
95
96 private Object selected;
97
98 @Override
99 public Object getSelectedItem() {
100 return selected;
101 }
102
103 @Override
104 public void setSelectedItem(Object anItem) {
105 if (anItem != null) {
106 selected = map.get(anItem.toString());
107 } else {
108 selected = anItem;
109 }
110 }
111
112 public Object getItem(String key) {
113 return map.get(key);
114 }
115
116 }