JComboBox setting label and value

前端 未结 5 1520
死守一世寂寞
死守一世寂寞 2020-11-29 11:01

Is it possible to set a value and a label to a JComboBox so I can show a label but get a value that is different?

For example in JavaScript I can do:

5条回答
  •  死守一世寂寞
    2020-11-29 11:56

    You can put any object inside of a JComboBox. By default, it uses the toString method of the object to display a label navigate in the combo box using the keyboard. So, the best way is probably to define and use appropriate objects inside the combo :

    public class ComboItem {
        private String value;
        private String label;
    
        public ComboItem(String value, String label) {
            this.value = value;
            this.label = label;
        }
    
        public String getValue() {
            return this.value;
        }
    
        public String getLabel() {
            return this.label;
        }
    
        @Override
        public String toString() {
            return label;
        }
    }
    

提交回复
热议问题