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.
我想要做的是模仿HTML Select标签。我想显示文本作为选项,但选中后,我会使用它的值。
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.
例如,我会有一个国家/地区名称列表。但是,当用户选择日本时,我想获取该国家/地区的区域设置代码。所以用户看到他们选择了日本,但我的代码将获得“ja_JP”或其他东西。
I am trying to avoid storing the Country Name and Locale Code in a HashMap or something.
我试图避免将国家名称和区域设置代码存储在HashMap或其他东西中。
2 个解决方案
#1
8
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.
创建一个包含显示名称和国家/地区代码的Country对象。您可以执行quick和dirty并覆盖toString以显示显示名称,然后在用户选择某些内容时根据需要检索代码。
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.
因为我很懒,所以遗漏了构造函数。如果您对覆盖toString不满意,您还可以创建自己的渲染器来处理Country对象,并通过新的getter使用显示。
#2
1
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.
我通常创建一个自定义对象来保存“值”并覆盖toString()以返回JComboBox应该显示的内容。或者,您可以编写自己的单元格渲染器。
#1
8
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.
创建一个包含显示名称和国家/地区代码的Country对象。您可以执行quick和dirty并覆盖toString以显示显示名称,然后在用户选择某些内容时根据需要检索代码。
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.
因为我很懒,所以遗漏了构造函数。如果您对覆盖toString不满意,您还可以创建自己的渲染器来处理Country对象,并通过新的getter使用显示。
#2
1
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.
我通常创建一个自定义对象来保存“值”并覆盖toString()以返回JComboBox应该显示的内容。或者,您可以编写自己的单元格渲染器。