如何获得用可编辑的JComboBox编写的值?
我一直在搜索,似乎每个人都只使用JComboBox#getSelectedItem
。 但我的combobox是可编辑的 ,用户可以输入任何内容 。 getSelectedItem
方法返回combobox中的一个实际项,而不是在字段中输入的字符串。
如果我的盒子包含“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()
。 不错的画。
也许你使用getSelectedItem
的方式有问题。 对我来说,这似乎工作得很好:
JComboBox combo = new JComboBox<>(new String[] {"bar", "item"}); combo.setEditable(true); JButton button = new JButton("Get"); button.addActionListener((ActionEvent e) -> { System.out.println(combo.getSelectedItem()); }); JFrame frame = new JFrame(); frame.setLayout(new FlowLayout()); frame.getContentPane().add(combo); frame.getContentPane().add(button); frame.pack(); frame.setVisible(true);
如果在选择其中一个预定义项目后单击该按钮,则会打印该项目,如果输入一些文本然后按下该按钮,则会打印该文本。