Search code examples
javajavafx-2javafx

JavaFX - ComboBox listener for its textfield


I'm not even sure how to correctly ask this question, but is it possible to add listener here (on this textfield within ComboBox), when ComboBox is set as editable:

enter image description here

Currently I'm using 2 kinds of listeners for ComboBox. Mouse and Change listener. MouseListener for clicks on ComboBox and ChangeListener for selection of items within ComboBox. But I have no idea what kind of listener should I use to listen for text entry.


Solution

  • If you are only interested in the editable area (TextField) of ComboBox, use ComboBox#getEditor().

    ComboBox combobox = new ComboBox();
    combobox.setEditable(true);
    combobox.getEditor().textProperty().addListener(new ChangeListener<String>() {
    
        @Override
        public void changed(ObservableValue<? extends String> observable, 
                                        String oldValue, String newValue) {
            System.out.println("Text changed");
        }
    });
    

    The last text will be set to ComboBox's valueProperty when the TextField loses its focus.