tags:

views:

246

answers:

2

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????

A: 

Try the following. When the user changes a value AND presses [ENTER], the old value is removed and the new one is added.

If you need to replace the value at the same position, you will have to provide your own model that supports adding values at a certain position.

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);
Peter Lang
Nice! but with your code ,I can delete one item not more than that,why??
Johanna
You are allowed to debug the code yourself to see what happening!
camickr
Not sure when you want to delete the row...If you want to delete it when the user clears the input, check for that before re-adding the element
Peter Lang
A: 

Read the tutorial How to Use Combo Boxes

Editable combo box, before and after the arrow button is clicked

Editable combo box, before and after the arrow button is clicked

See the : Using an Editable Combo Box section.

Snippet from that page:

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