Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to make a JComboBox act like an HTML Select?

What I am trying to do mimic an HTML Select tag. I want to display text as an option but when selected, I would use its value.

For example, I would have a list of country names. However, when a user selects Japan, I want to get the Locale Code for that country. So the user sees that they selected Japan, but my code will get "ja_JP" or something.

I am trying to avoid storing the Country Name and Locale Code in a HashMap or something.

like image 551
Ascalonian Avatar asked Jan 23 '23 19:01

Ascalonian


1 Answers

Create a Country object which contains the display name and the country code. You could do the quick and dirty and override toString to show the display name and then just retrieve the code when you need it when the user selects something.

public class Country
{
    String display;
    String code;

    @Override
    public String toString()
    {
        return display;
    }

    public String getCode()
    {
        return code;
    }
}

Left out the constructor as I am lazy. If you are not happy with overriding toString you could also create your own renderer that deals with Country objects and use the display instead through a new getter.

like image 119
willcodejavaforfood Avatar answered Jan 26 '23 09:01

willcodejavaforfood