我一直在搜索,似乎每个人都只使用 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();
}
});
结果是这样的:
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
如您所见, Action 事件监听器可以捕获值,但按键事件不能。
最佳答案
这种方式:combobox.getEditor().getItem()
。画得不错。
关于java - 如何获取已写入可编辑JComboBox 中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29104743/