Adding items to a JComboBox

后端 未结 6 658
生来不讨喜
生来不讨喜 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:55

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

提交回复
热议问题