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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With