Note that there are some explanatory texts on larger screens.

plurals
  1. PONeed flexible Java key/value collection class for JComboBox
    text
    copied!<p>I have a model class that stores keys and values:</p> <pre><code>public class KeyValue { private Object key; private String value; KeyValue () { } KeyValue (Object key, String value) { this.key=key; this.value=value; } public Object getKey() { return this.key; } public void setKey(Object key) { this.key=key; } public String getValue() { return this.value; } public void setValue(String value) { this.value=value; } @Override public String toString() { return this.value; } } </code></pre> <p>I use this class to populate a <code>JComboBox</code>'s Model:</p> <pre><code>for (int i = 0; i &lt; universes.length; i++) { ComboBox_Universes.addItem(new KeyValue(infoObject.ID,infoObject.title)); } </code></pre> <p>I would like to refactor this logic to use a Java collection class (call it <code>KeyValueCollection</code>) that can support two objectives:</p> <p>1) the <code>KeyValueCollection</code> can be used to populate the <code>JComboBox</code>'s Model. Something like:</p> <pre><code>//get a KeyValueCollection filled with data from helper class KeyValueCollection universeCollection = Repository.getUniverseCollection(); //use this collection as the JComboBox's model ComboBox_Universes.setModel(universeCollection); </code></pre> <p>2) I can use the <code>KeyValueCollection</code> to convert a key to a value:</p> <pre><code>//ID retrieve from another control int universeID = (int)this.Table_Values.getModel().getValueAt(row, COLUMN_ID); //convert ID to name String universeName = universeCollection.get(universeID).getValue(); </code></pre> <p>In the .NET world, I would use the KeyedCollection class for this, but I'm not very familiar with Java.</p> <p>Help is greatly appreciated.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload