JavaFX - ComboBox listener for its textfield


Question

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.

1
2
12/16/2017 12:56:21 PM

Accepted Answer

If you 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 looses its focus.

6
9/6/2013 12:35:02 PM

In JavaFX, you can attach notification events to any property that a control may possess. In your case, you need to decide if you want to be notified if the combobox's editable value field changes or if you want to receive key events each time the user enters a key into the value field.

If you simply wish to act on an event in the case that the combobox's value field changes, you can register a ChangeListener for its valueProperty which is defined in the Javadocs as follows:

valueProperty: The value of this ComboBox is defined as the selected item if the input is not editable, or if it is editable, the most recent user action: either the value input by the user, or the last selected item.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon