我一直在寻找,似乎每个人都只使用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事件侦听器可以捕获值,但键事件不能.
| 归档时间: |
|
| 查看次数: |
6916 次 |
| 最近记录: |