/Users/lyon/j4p/src/javagroup/swing/HistoryComboModel.java
|
1 package javagroup.swing;
2
3 import javax.swing.*;
4
5 /**
6 * A combo-box model that keeps a history of items that have been entered
7 * into the box in the past. Items are not duplicated, but are moved to
8 * the top of the list as they are re-entered.
9 * <p/>
10 * <p>This class includes an ActionListener inner class that can be
11 * attached to the combo box to automatically insert entries into the
12 * history list as they are entered.
13 *
14 * @author Martin Pool
15 * @version $Revision: 1.2 $, $Date: 1999/01/05 11:47:21 $
16 */
17 public class HistoryComboModel
18 extends DefaultListModel
19 implements ComboBoxModel {
20 /**
21 * Current selection *
22 */
23 protected Object sel_;
24
25 public void setSelectedItem(Object anItem) {
26 sel_ = anItem;
27 fireContentsChanged(this, -1, -1);
28 }
29
30 public Object getSelectedItem() {
31 return sel_;
32 }
33
34 /**
35 * Add an entry to the top of the history list. This method should be
36 * called whenever the application thinks the user has finished adding
37 * something significant to the combo box: for example, when they press
38 * the "Ok" button. *
39 */
40 public synchronized void addToHistory(String toAdd) {
41 // If the string is already present in the history, remove it
42 for (int i = 0; i < getSize();) {
43 if (getElementAt(i).equals(toAdd))
44 removeElementAt(i);
45 else
46 i++;
47 }
48
49 // Add to the start of the history
50 insertElementAt(toAdd, 0);
51
52 // In general, everything changed
53 fireContentsChanged(this, -1, -1);
54 }
55 }
56
57
58