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

前端 未结 3 974
一向
一向 2020-12-25 14:49

I have an editable JComboBox where I want to take some action whenever the text is changed, either by typing or selection. In this case, the text is a pattern and

相关标签:
3条回答
  • 2020-12-25 15:26

    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 ...
    });
    
    0 讨论(0)
  • 2020-12-25 15:26

    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
            }
        }
    });
    
    0 讨论(0)
  • 2020-12-25 15:50

    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:
    
    }    });
    
    0 讨论(0)
提交回复
热议问题