java-可编辑的JComboBox
作者:互联网
如果用户选择索引为1的项目,然后将其从“ 123”更改为“ abcd”.如何设置“ abcd”而不是“ 123”(在NetBeans中)?另外,如何永久删除该项目?
解决方法:
请尝试以下方法.当用户更改值并按[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);
标签:jcombobox,java 来源: https://codeday.me/bug/20191210/2101449.html