如何获取已写入可编辑JComboBox 中的值?

How to get value that has been written in editable JComboBox?

我一直在搜索,似乎每个人都只使用 JComboBox#getSelectedItem。但是我的组合框是可编辑,用户可以输入任何内容getSelectedItem 方法 return 是组合框中的实际项目之一,而不是在字段中输入的字符串。

如果我的盒子包含“Bar”和“Item”并且用户输入“Foo”,我想得到“Foo”!

为什么 getSelectedItem 不起作用

有人指出 getSelectedItem 也会 return 输入的字符串。但没有指出,这仅在用户停止编辑该字段后才有效。我附加了这些事件侦听器:

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

如您所见,动作事件监听器可以捕获值,但按键事件不能。

这样:combobox.getEditor().getItem()。画的不错

可能您使用的方式有问题getSelectedItem。对我来说,这似乎工作得很好:

JComboBox<String> 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);

如果您在选择一个预定义项目后单击按钮,它会打印该项目,如果您输入一些文本然后按下按钮,它会打印该文本。