Adding items to a JComboBox

后端 未结 6 702
生来不讨喜
生来不讨喜 2020-12-01 18:16

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

6条回答
  •  不知归路
    2020-12-01 18:52

    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();
    

提交回复
热议问题