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

前端 未结 3 975
一向
一向 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

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

提交回复
热议问题