java 可编辑的 JComboBox
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1789656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Editable JComboBox
提问by Johanna
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?
如果用户选择其索引为 1 的项目,并将其从“123”更改为“abcd”。如何设置“abcd”而不是“123”(在 NetBeans 中)?另外我怎样才能永远删除该项目?
回答by Peter Lang
Try the following. When the user changes a value AND presses [ENTER], the old value is removed and the new one is added.
请尝试以下操作。当用户更改值并按下 [ENTER] 时,旧值将被删除并添加新值。
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);
回答by OscarRyz
Read the tutorial How to Use Combo Boxes
阅读教程如何使用组合框
Editable combo box, before and after the arrow button is clicked
可编辑的组合框,在单击箭头按钮之前和之后
See the : Using an Editable Combo Boxsection.
请参阅: 使用可编辑组合框部分。
Snippet from that page:
该页面的片段:
JComboBox patternList = new JComboBox(patternExamples);
patternList.setEditable(true);
patternList.addActionListener(this);


