Search code examples
javaswingjcombobox

Adding items to a JComboBox


I use a combo box on panel and as I know we can add items with the text only

    comboBox.addItem('item text');

But some times I need to use some value of the item and item text like in html select:

    <select><option value="item_value">Item Text</option></select>

Is there any way to set both value and title in combo box item?

For now I use a hash to solve this issue.


Solution

  • Wrap the values in a class and override the toString() method.

    class ComboItem
    {
        private String key;
        private String value;
    
        public ComboItem(String key, String value)
        {
            this.key = key;
            this.value = value;
        }
    
        @Override
        public String toString()
        {
            return key;
        }
    
        public String getKey()
        {
            return key;
        }
    
        public String getValue()
        {
            return value;
        }
    }
    

    Add the ComboItem to your comboBox.

    comboBox.addItem(new ComboItem("Visible String 1", "Value 1"));
    comboBox.addItem(new ComboItem("Visible String 2", "Value 2"));
    comboBox.addItem(new ComboItem("Visible String 3", "Value 3"));
    

    Whenever you get the selected item.

    Object item = comboBox.getSelectedItem();
    String value = ((ComboItem)item).getValue();