【发布时间】:2015-03-17 16:37:51
【问题描述】:
我一直在搜索,似乎每个人都只使用JComboBox#getSelectedItem。但我的组合框是可编辑,用户可以输入anything。 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();
}
});
结果如下:
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
如您所见,动作事件侦听器可以捕获值,但键事件不能。
【问题讨论】:
-
getSelectedItem对我来说似乎工作得很好。也许你应该给我们看一些代码。 -
实际上,你能把对你有用的代码贴在某个地方吗?
-
另外,看起来它是一个副本:stackoverflow.com/questions/10072335/…
-
我已经澄清了为什么
getSelectedItem不起作用。被链接的重复问题确实询问“Get input values from JComboBox”,这给人的印象是它在要求其他东西。也许这就是我没有找到它的原因。