3

If the user select the item which its index is 1,and change it from"123" to "abcd".how can I set "abcd" instead of "123" (in NetBeans)? Also how can I delete the item for ever?

4

2 回答 2

3

试试下面的。当用户更改值并按下 [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);
于 2009-11-24T12:43:58.340 回答
0

阅读教程如何使用组合框

可编辑的组合框,在单击箭头按钮之前和之后

可编辑的组合框,在单击箭头按钮之前和之后

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

该页面的片段:

JComboBox patternList = new JComboBox(patternExamples);
patternList.setEditable(true);
patternList.addActionListener(this);
于 2009-11-24T12:52:44.343 回答