2009-11-24 73 views
1

如果用户选择其索引为1的项目,并将其从“123”更改为“abcd”。如何设置“abcd”而不是“123”(在NetBeans中)?另外我怎样才能永久删除该项目?可编辑JComboBox

+0

你说的一套 “ABCD” 的意思。你想改变模型的价值吗?如果是这样,你使用什么模型? – 2009-11-24 12:12:49

+0

我的意思是我想永远改变“123”到“abcd”。 还我使用默认的模型,并用setEditable(真)我做它既然你不读你的其他帖子给出的建议,这似乎有待时间来提出一个建议在此张贴的浪费可编辑ComboBox – Johanna 2009-11-24 12:21:23

+0

。 – camickr 2009-11-24 16:53:44

回答

1

请尝试以下操作。当用户更改一个值并按下[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); 
+0

不错!但用你的代码,我可以删除一个不超过这个的项目,为什么? – Johanna 2009-11-25 03:47:38

+0

您可以自行调试代码以查看发生了什么! – camickr 2009-11-25 04:49:26

+0

不确定何时删除该行... 如果要在用户清除输入时删除它,请在重新添加元素之前检查该元素 – 2009-11-25 09:23:55