将项添加到JComboBox [英] Adding items to a JComboBox
本文介绍了将项添加到JComboBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在面板上使用了一个组合框,据我所知,我们只能添加带文字的项目
I use a combo box on panel and as I know we can add items with the text only
comboBox.addItem('item text');
但有时我需要使用项目和项目文本的某些值,如在html中选择:
But some times I need to use some value of the item and item text like in html select:
<select><option value="item_value">Item Text</option></select>
有没有办法在组合框项目中设置值和标题?
Is there any way to set both value and title in combo box item?
现在我使用哈希来解决这个问题。
For now I use a hash to solve this issue.
推荐答案
将值包装在一个class并覆盖 toString()
方法。
Wrap the values in a class and override the toString()
method.
class ComboItem
{
private String key;
private String value;
public ComboItem(String key, String value)
{
this.key = key;
this.value = value;
}
@Override
public String toString()
{
return key;
}
public String getKey()
{
return key;
}
public String getValue()
{
return value;
}
}
将ComboItem添加到您的comboBox。
Add the ComboItem to your comboBox.
comboBox.addItem(new ComboItem("Visible String 1", "Value 1"));
comboBox.addItem(new ComboItem("Visible String 2", "Value 2"));
comboBox.addItem(new ComboItem("Visible String 3", "Value 3"));
每当你得到所选项目时。
Whenever you get the selected item.
Object item = comboBox.getSelectedItem();
String value = ((ComboItem)item).getValue();
这篇关于将项添加到JComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文