如何获得用可编辑的JComboBox编写的值?

时间:2015-03-17 16:37:51

标签: java jcombobox

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

image description

如果我的包含" Bar"和"项目"并且用户输入" 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事件侦听器可以捕获值,但键事件不能。

2 个答案:

答案 0 :(得分:12)

这样:combobox.getEditor().getItem()。好画。

答案 1 :(得分:1)

使用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);

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

相关问题