Adding items to a JComboBox

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

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

提交回复
热议问题