How can I know when the text of an editable JComboBox has been changed?

天大地大妈咪最大 提交于 2019-11-30 01:53:18

The action listener is typically only fired when you hit enter, or move focus away from the editor of the combobox. The correct way to intercept individual changes to the editor is to register a document listener:

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

The DocumentListener interface has methods that are called whenever the Document backing the editor is modified (insertUpdate, removeUpdate, changeUpdate).

You can also use an anonymous class for finer-grained control of where events are coming from:

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 ...
});

You can use somthing like this:

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
        }
    }
});

this sounds like the best solution

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

}    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!