[1] | 1 | package genius.gui.panels;
|
---|
| 2 |
|
---|
| 3 | import java.util.ArrayList;
|
---|
| 4 | import java.util.List;
|
---|
| 5 |
|
---|
| 6 | import javax.swing.DefaultComboBoxModel;
|
---|
| 7 | import 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")
|
---|
| 22 | public 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 | }
|
---|