我继续搜索,似乎每个人都只使用JComboBox#getSelectedItem
。但我的组合框是editable用户可以输入anything. The getSelectedItem
方法返回组合框中的实际项目之一,而不是在字段中输入的字符串。
如果我的盒子包含“Bar”和“Item”并且用户输入“Foo”,我想得到“Foo”!
Why 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();
}
});
结果如下:
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
正如您所看到的,操作事件侦听器可以捕获该值,但按键事件却不能。
这边走:combobox.getEditor().getItem()
。画得不错。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)