2012-07-02 61 views
-1

我想要的功能更新当前项目中JComboBox的Java JComboBox.setSelectedItem()不更新下拉列表

@Override 
public void updateId(String id) { 
    boolean old = notify; 
    notify = false; 
    comboBox.setEditable(true); 
    comboBox.setSelectedItem(id); 
    comboBox.setEditable(false); 
    notify = old; 
} 

结果是这样的:

image

  1. 组合框是绑定到文本框,
  2. 我更改文本框的值,它调用updateId(),
  3. 扩展组合框,即得到了改变
  4. 选择项目,

组合框的下拉列表中没有反映到选定的项目进行了更改;在给定的例子中,在下拉列表的底部应该有“xxx”。

+1

你是如何增加新的字符串到ComboBox? – Evans

+3

请修改您的问题以包含展示您描述的问题的[sscce](http://sscce.org/)。 – trashgod

+0

@Override \t public void add(String id){ \t \t comboBox.addItem(id); \t} – drag0nius

回答

1

我误解了JComboBox.setSelectedItem()

它听起来像是它应该重写项目在选择的模型索引下,当组合框是可编辑的,但它只是覆盖显示的值,并且不会触摸模型。

这一个做这项工作:

@Override 
    public void updateId(String id) { 
     boolean old = notify; 
     notify = false; 
     comboBox.setEditable(true); 

     DefaultComboBoxModel<String> model = (DefaultComboBoxModel<String>) comboBox.getModel(); 
     int selectedIndex = comboBox.getSelectedIndex(); 
     model.removeElementAt(selectedIndex); 
     model.insertElementAt(id, selectedIndex); 
     comboBox.setSelectedIndex(selectedIndex); 

     comboBox.setEditable(false); 
     notify = old; 
    }