19

我有一个可编辑的JComboBox,只要通过键入或选择更改文本,我就想在其中执行一些操作。在这种情况下,文本是一个模式,我想验证该模式是否有效并显示导致某些测试数据的匹配项。

完成了明显的操作,附加一个 ActionHandler,我发现,对于打字,事件似乎不可靠地触发,充其量是(选择很好)。当它因键入而触发时,检索到的文本(使用 getEditor().getItem(),因为 getSelectedItem() 仅在从列表中选择文本时才获取文本)似乎是文本,因为它是最后一个事件被触发 - 也就是说,它总是缺少在触发动作事件之前立即输入的字符。

我期待动作事件在一些短暂的延迟(500 毫秒到 1 秒)后触发,但它似乎在键控时立即触发(如果它被触发的话)。

我能想到的唯一可行的替代方法是简单地在获得焦点时启动一个 1 秒计时器,在失去焦点时将其终止,如果内容与上次不同,则将其作为计时器动作进行工作。

有什么想法或建议吗?

代码片段并不是特别有趣:

find.addActionListener(this);
...
public void actionPerformed(ActionEvent evt) {
    System.out.println("Find: "+find.getEditor().getItem());
    }
4

3 回答 3

31

动作侦听器通常仅在您按下回车键或将焦点从组合框的编辑器移开时才会触发。拦截对编辑器的个别更改的正确方法是注册一个文档侦听器:

final JTextComponent tc = (JTextComponent) combo.getEditor().getEditorComponent();
tc.getDocument().addDocumentListener(this);

DocumentListener 接口具有在支持编辑器的 Document 被修改时调用的方法(insertUpdate、removeUpdate、changeUpdate)。

您还可以使用匿名类来更细粒度地控制事件的来源:

final JTextComponent tcA = (JTextComponent) comboA.getEditor().getEditorComponent();
tcA.getDocument().addDocumentListener(new DocumentListener() { 
  ... code that uses comboA ...
});

final JTextComponent tcB = (JTextComponent) comboB.getEditor().getEditorComponent();
tcB.getDocument().addDocumentListener(new DocumentListener() { 
  ... code that uses comboB ...
});
于 2009-08-10T02:09:45.413 回答
-1

你可以使用这样的东西:

JComboBox cbListText = new JComboBox();
cbListText.addItem("1");
cbListText.addItem("2");
cbListText.setEditable(true);
final JTextField tfListText = (JTextField) cbListText.getEditor().getEditorComponent();
tfListText.addCaretListener(new CaretListener() {
    private String lastText;

    @Override
    public void caretUpdate(CaretEvent e) {
        String text = tfListText.getText();
        if (!text.equals(lastText)) {
            lastText = text;
            // HERE YOU CAN WRITE YOUR CODE
        }
    }
});
于 2012-12-06T12:57:52.603 回答
-1

这听起来像是最好的解决方案

jComboBox.getEditor().getEditorComponent().addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {    //add your hadling code here:

}    });
于 2016-12-11T06:52:39.563 回答