如何获得用可编辑的JComboBox编写的值?

Tom*_*ica 11 java jcombobox

我一直在寻找,似乎每个人都只使用JComboBox#getSelectedItem.但我的组合框是可编辑的,用户可以输入任何内容.该getSelectedItem方法返回组合框中的一个实际项目,而不是在字段中输入的字符串.

图片描述

如果我的盒子包含"Bar"和"Item"并且用户输入"Foo",我想得到"Foo"!

为什么getSelectedItem不起作用

有人指出,getSelectedItem它也会返回输入的字符串.但是没有指出,这仅在用户停止编辑字段后才有效.我附上了这些事件监听器:

Component[] comps = input.getComponents();
//Third is the text field component
comps[2].addKeyListener(new KeyListener() {
  public void keyTyped(KeyEvent e) {
    doSomething();
  }
});
//Also fire event after user leaves the field
input.addActionListener (new ActionListener () {
    @Override
    public void actionPerformed(ActionEvent e) {
      doSomething();
    }
});
Run Code Online (Sandbox Code Playgroud)

这就是结果:

KeyEvent:
 JComboBox.getEditor().getItem() = 6  
 JComboBox.getSelectedItem()     = null
KeyEvent:
 JComboBox.getEditor().getItem() = 66
 JComboBox.getSelectedItem()     = null
KeyEvent:
 JComboBox.getEditor().getItem() = 666
 JComboBox.getSelectedItem()     = null
ActionEvent:
 JComboBox.getEditor().getItem() = 6666
 JComboBox.getSelectedItem()     = 6666
Run Code Online (Sandbox Code Playgroud)

如您所见,action事件侦听器可以捕获值,但键事件不能.

Umb*_*ndi 14

这样:combobox.getEditor().getItem().不错的画.