【问题标题】:Java JComboBox.setSelectedItem() not updating dropdown listJava JComboBox.setSelectedItem() 不更新下拉列表
【发布时间】:2012-07-02 15:19:25
【问题描述】:

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

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

结果是这样的:

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

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

【问题讨论】:

  • 如何将新字符串添加到组合框?
  • 请编辑您的问题,在sscce 中包含您所描述的问题。
  • @Override public void add(String id) { comboBox.addItem(id); }
  • 请将您的解决方案写成正确的答案并接受它,以便将问题标记为已解决

标签: java swing jcombobox selecteditem


【解决方案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;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 2019-01-23
    • 2020-06-27
    • 2015-08-03
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多