2012-07-02 64 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; 
    }