[java] 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.

This question is related to java swing jcombobox

The answer is


addItem(Object) takes an object. The default JComboBox renderer calls toString() on that object and that's what it shows as the label.

So, don't pass in a String to addItem(). Pass in an object whose toString() method returns the label you want. The object can contain any number of other data fields also.

Try passing this into your combobox and see how it renders. getSelectedItem() will return the object, which you can cast back to Widget to get the value from.

public final class Widget {
    private final int value;
    private final String label;

    public Widget(int value, String label) {
        this.value = value;
        this.label = label;
    }

    public int getValue() {
        return this.value;
    }

    public String toString() {
        return this.label;
    }
}

You can use String arrays to add jComboBox items

String [] items = { "First item", "Second item", "Third item", "Fourth item" };

JComboBox comboOne = new JComboBox (items);

You can use any Object as an item. In that object you can have several fields you need. In your case the value field. You have to override the toString() method to represent the text. In your case "item text". See the example:

public class AnyObject {

    private String value;
    private String text;

    public AnyObject(String value, String text) {
        this.value = value;
        this.text = text;
    }

...

    @Override
    public String toString() {
        return text;
    }
}

comboBox.addItem(new AnyObject("item_value", "item text"));

create a new class called ComboKeyValue.java

    public class ComboKeyValue {
        private String key;
        private String value;
    
        public ComboKeyValue(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;
        }
}

when you want to add a new item, just write the code as below

 DefaultComboBoxModel model = new DefaultComboBoxModel();
    model.addElement(new ComboKeyValue("key", "value"));
    properties.setModel(model);

Method call setSelectedIndex("item_value"); doesn't work because setSelectedIndex use sequential index.