views:

223

answers:

2

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.

+8  A: 

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.

willcodejavaforfood
+1  A: 

EDIT: I need to type faster.

I usually create a custom object to hold the "value" and override toString() to return what the JComboBox should show. Alternately, you could write your own cell renderer.

basszero
No one out-types me! :)
willcodejavaforfood