我在面板上使用组合框,据我所知我们可以添加仅包含文本的项目
comboBox.addItem('item text');
但有时我需要使用项目的某些值和项目文本,例如在 html 选择中:
<select><option value="item_value">Item Text</option></select>
有什么方法可以同时设置组合框项目的值和标题吗?
目前我使用哈希来解决这个问题。
最佳答案
将值包装在类中并覆盖 toString()
方法。
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.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"));
每当您获得所选项目时。
Object item = comboBox.getSelectedItem();
String value = ((ComboItem)item).getValue();
关于java - 将项目添加到 JComboBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17887927/