【问题标题】:Editable JComboBox可编辑的 JComboBox
【发布时间】:2010-12-19 20:47:33
【问题描述】:

如果用户选择其索引为 1 的项目,并将其从“123”更改为“abcd”。如何设置“abcd”而不是“123”(在 NetBeans 中)?另外,我怎样才能永远删除该项目?

【问题讨论】:

  • 设置“abcd”是什么意思。您想更改模型中的值吗?如果是这样,您使用什么型号?
  • 我的意思是我想永远把“123”改成“abcd”。我也使用默认模型并使用 setEditable(true) 将其设置为可编辑的 ComboBox
  • 鉴于您没有阅读其他帖子中给出的建议,因此在此帖子中提出建议似乎是浪费时间。

标签: java jcombobox


【解决方案1】:

试试下面的。当用户更改值并按下 [ENTER] 时,旧值将被删除并添加新值。

如果您需要替换相同位置的值,则必须提供自己的模型,支持在某个位置添加值。

final DefaultComboBoxModel model = new DefaultComboBoxModel(new String[] {"Red", "Green", "Blue"});

comboBox = new JComboBox(model);
comboBox.setEditable(true);
comboBox.addActionListener(new ActionListener() {
    private int selectedIndex = -1;

    @Override
    public void actionPerformed(ActionEvent e) {
        int index = comboBox.getSelectedIndex();
        if(index >= 0) {
            selectedIndex = index;
        }
        else if("comboBoxEdited".equals(e.getActionCommand())) {
            Object newValue = model.getSelectedItem();
            model.removeElementAt(selectedIndex);
            model.addElement(newValue);
            comboBox.setSelectedItem(newValue);
            selectedIndex = model.getIndexOf(newValue);
        }
    }
});
comboBox.setSelectedIndex(0);

【讨论】:

  • 不错!但是使用您的代码,我最多只能删除一项,为什么??
  • 你可以自己调试代码看看发生了什么!
  • 不确定何时要删除该行...如果您想在用户清除输入时删除它,请在重新添加元素之前进行检查
  • 谢谢!另请注意,编辑时选择的索引是-1
【解决方案2】:

阅读教程How to Use Combo Boxes

可编辑组合框,前后 箭头按钮被点击

请参阅:使用可编辑组合框部分。

该页面的片段:

JComboBox patternList = new JComboBox(patternExamples);
patternList.setEditable(true);
patternList.addActionListener(this);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 2012-01-16
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    相关资源
    最近更新 更多