Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editable JComboBox

Tags:

java

jcombobox

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?

like image 794
Johanna Avatar asked Oct 15 '25 03:10

Johanna


1 Answers

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);
like image 99
Peter Lang Avatar answered Oct 17 '25 09:10

Peter Lang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!