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

标签 java jcombobox

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

image description

如果我的盒子包含“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/

相关文章:

java - 如何获取网站内容并将其以我们想要的方式放入 android 应用程序布局中?

java - 添加项目时 JComboBox 错误

java - 即使根本没有引用,JCombobox 内存泄漏?

java - 在调用Java中的 super 构造函数之前做一些逻辑

java - 如何按难度级别显示所有问题

java - 连接更改接收器在 android 中获得错误 Intent

java - 最终变量的理解

java - 阶梯式组合框刷新

java - swing 应用程序中线程 "AWT-EventQueue-0"java.lang.NullPointerException 中的异常

java - 是否可以自定义 JTree 节点?