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

时间:2012-07-02 15:19:26

标签: 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;
}

结果如下:

image

  1. ComboBox绑定到文本框,
  2. 我更改了文本框值,即调用updateId(),
  3. 扩展组合框,
  4. 选择已更改的项目,
  5. 组合的下拉列表不反映对所选项目所做的更改;在给定的示例中,下拉列表底部应该有“xxx”。

1 个答案:

答案 0 :(得分: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;
    }
相关问题