001: /*
002: * Copyright (C) 2005 Jeff Tassin
003: *
004: * This library is free software; you can redistribute it and/or
005: * modify it under the terms of the GNU Lesser General Public
006: * License as published by the Free Software Foundation; either
007: * version 2.1 of the License, or (at your option) any later version.
008: *
009: * This library is distributed in the hope that it will be useful,
010: * but WITHOUT ANY WARRANTY; without even the implied warranty of
011: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012: * Lesser General Public License for more details.
013: *
014: * You should have received a copy of the GNU Lesser General Public
015: * License along with this library; if not, write to the Free Software
016: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
017: */
018:
019: package com.jeta.swingbuilder.gui.utils;
020:
021: import java.util.Iterator;
022: import java.util.LinkedList;
023:
024: import javax.swing.JComboBox;
025:
026: /**
027: * Very often we have JComboBoxes that are loaded with String values but which
028: * map to integers. So, we use this helper class to make using combo boxes in
029: * these situations a little easier.
030: *
031: * @author Jeff Tassin
032: */
033: public class IntegerComboMap {
034: /**
035: * The actual map
036: */
037: private LinkedList m_map = new LinkedList();
038:
039: /**
040: * Assigns a combo box item to an integer value
041: */
042: public void map(int key, String comboItem) {
043: Iterator iter = m_map.iterator();
044: while (iter.hasNext()) {
045: KeyValuePair kv = (KeyValuePair) iter.next();
046: if (kv.key == key)
047: iter.remove();
048: }
049: m_map.add(new KeyValuePair(key, comboItem));
050: }
051:
052: /**
053: * @return the selected map value. -1 is returned if no item is selected in
054: * the box or no match is found in this map for the selected item in
055: * the combo.
056: */
057: public int getSelectedValue(JComboBox cbox) {
058: if (cbox == null)
059: return -1;
060:
061: Object value = cbox.getSelectedItem();
062: if (value == null)
063: return -1;
064:
065: Iterator iter = m_map.iterator();
066: while (iter.hasNext()) {
067: KeyValuePair kv = (KeyValuePair) iter.next();
068: if (value.equals(kv.value))
069: return kv.key;
070: }
071: return -1;
072: }
073:
074: /**
075: * Sets the selected item in the combo box using the key.
076: */
077: public void setSelectedItem(JComboBox cbox, int key) {
078: if (cbox == null)
079: return;
080:
081: Iterator iter = m_map.iterator();
082: while (iter.hasNext()) {
083: KeyValuePair kv = (KeyValuePair) iter.next();
084: if (key == kv.key) {
085: cbox.setSelectedItem(kv.value);
086: return;
087: }
088: }
089: }
090:
091: private static class KeyValuePair {
092: Object value;
093: int key;
094:
095: KeyValuePair(int key, Object value) {
096: this.key = key;
097: this.value = value;
098: }
099: }
100: }
|