Adding items to a JComboBox

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

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

提交回复
热议问题