Java JComboBox.setSelectedItem()未更新下拉列表

Java JComboBox.setSelectedItem()未更新下拉列表,java,swing,jcombobox,selecteditem,Java,Swing,Jcombobox,Selecteditem,我想让函数更新JComboBox中的当前项: @Override public void updateId(String id) { boolean old = notify; notify = false; comboBox.setEditable(true); comboBox.setSelectedItem(id); comboBox.setEditable(false); notify = old; } 结果是: ComboBox绑定到

我想让函数更新
JComboBox
中的当前项:

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

  • ComboBox绑定到textbox
  • 我更改textbox值,该值调用updateId()
  • 正在扩展组合框
  • 正在选择已更改的项目

  • 组合的下拉列表不反映对所选项目所做的更改;在给定的示例中,下拉列表底部应该有“xxx”。

    我误解了
    JComboBox.setSelectedItem()

    当combobox是可编辑的时,它听起来应该覆盖模型的选定索引下的项目,但它只覆盖显示的值,不接触模型

    这个就可以了:

        @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;
        }
    
    @覆盖
    公共void updateId(字符串id){
    布尔旧=通知;
    通知=假;
    comboBox.setEditable(真);
    DefaultComboxModel=(DefaultComboxModel)comboBox.getModel();
    int-selectedIndex=comboBox.getSelectedIndex();
    model.removeElementAt(selectedIndex);
    model.insertElementAt(id,selectedIndex);
    组合框。设置selectedIndex(selectedIndex);
    comboBox.setEditable(false);
    通知=旧;
    }
    
    如何将新字符串添加到组合框中?请编辑您的问题,以包含一个显示您描述的问题的字符串。@Override public void add(字符串id){comboBox.addItem(id);}请将您的解决方案作为正确答案写入并接受,以便将问题标记为已解决