如何获得用可编辑的JComboBox编写的值? [英] How to get value that has been written in editable JComboBox?
问题描述
我一直在搜索,似乎每个人都只使用 JComboBox#getSelectedItem
。但我的组合框可编辑,用户可以输入任何内容。 getSelectedItem
方法返回组合框中的一个实际项目,而不是字段中输入的字符串。
I keep searching and it seems like everybody is using only the JComboBox#getSelectedItem
. But my combo box is editable and the user can enter anything. The getSelectedItem
method returns one of the actual items in the combo box, not a string entered in the field.
如果我的包含Bar和项目和用户输入Foo,我想得到Foo!
If my box contains "Bar" and "Item" and user enters "Foo", I want to get "Foo"!
有人指出 getSelectedItem
也会返回输入的字符串。但是没有指出,这仅在用户停止编辑字段后才有效。我附加了这些事件监听器:
It was pointed out that getSelectedItem
does also return the string entered. It was not pointed out though, that this only works after the user stops editing the field. I attached these event listeners:
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
如您所见,动作事件监听器可以捕获值,但关键事件不能。
As you can see, the action event listener could capture the value, but the key event could not.
推荐答案
这样: combobox.getEditor()。getItem()
。不错的画作。
这篇关于如何获得用可编辑的JComboBox编写的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!