source: src/main/java/genius/gui/panels/SingleSelectionModel.java@ 346

Last change on this file since 346 was 1, checked in by Wouter Pasman, 6 years ago

Initial import : Genius 9.0.0

File size: 1.7 KB
Line 
1package genius.gui.panels;
2
3import java.util.ArrayList;
4import java.util.List;
5
6import javax.swing.DefaultComboBoxModel;
7import javax.swing.event.ListDataListener;
8
9/**
10 * A model where the user can select a single item from a list of a given type.
11 * This object can be listened for changes made by the user. Changes can also be
12 * made programmatically.
13 *
14 * <p>
15 * To listen for selection changes, attach and use the callback in
16 * {@link ListDataListener#contentsChanged(javax.swing.event.ListDataEvent)}.
17 *
18 * @param <ItemType>
19 * the type of item that this model contains.
20 */
21@SuppressWarnings("serial")
22public class SingleSelectionModel<ItemType> extends DefaultComboBoxModel<ItemType> {
23
24 public SingleSelectionModel(List<ItemType> allItems) {
25 setAllItems(allItems);
26 }
27
28 /**
29 * use new set of possible items.
30 *
31 * @param allItems
32 */
33 public void setAllItems(List<ItemType> allItems) {
34 removeAllElements();
35 for (ItemType item : allItems) {
36 addElement(item);
37 }
38 if (!allItems.isEmpty()) {
39 setSelectedItem(allItems.get(0));
40 }
41 }
42
43 /**
44 *
45 * @return all items that can be chosen.
46 */
47 public List<ItemType> getAllItems() {
48 ArrayList<ItemType> list = new ArrayList<ItemType>();
49 for (int n = 0; n < getSize(); n++) {
50 list.add(getElementAt(n));
51 }
52 return list;
53 }
54
55 /**
56 * Type-checked version of {@link #getSelectedItem()}
57 *
58 * @return selected item.
59 */
60 @SuppressWarnings("unchecked")
61 public ItemType getSelection() {
62 return (ItemType) getSelectedItem();
63 }
64
65 /**
66 * Select the next element in the list.
67 */
68 public void increment() {
69 int n = getIndexOf(getSelectedItem());
70 if (n + 1 < getSize()) {
71 setSelectedItem(getElementAt(n + 1));
72 }
73 }
74
75}
Note: See TracBrowser for help on using the repository browser.