Java: Use Key/Value Pair For JComboBox Like HTML’s Select Tag

By default, Java’s JComboBox does not have the same feature as the HTML dropdown’s SELECT tag. You know the label and value in the OPTION tag. If you want to have the same feature for the JComboBox, you would have to ceate your own KeyValue class that contains the key (label) and the value. See the code below.

Make sure the toString() method returns the variable key so that it will be what will appear in the JComboBox’s list. To add it to the JComboBox, do it like this.

To get the selected item, do this.

Related Posts Plugin for WordPress, Blogger...

3 comments

Leave a Reply

Your email address will not be published. Required fields are marked *