Search code examples
javafxcomboboxtextfield

JavaFx: How can I get the combobox object from it's textfield?


I have a combobox (cb). When someone clicks on the associated textfield, I want to clear it. I use

cb.getEditor().setOnMousePressed(new EventHandler<MouseEvent>() {
    @Override
    public void handle(MouseEvent evt) {
        ((TextField) evt.getSource()).clear();
    }
});

and the result is in cb.getEditor().getText() So far so good.
If I fill the box via the pull down instead of typing the result is in cb.getSelectionModel().getSelectedIndex();
That's good too. The combobox is populated with an object, not a string, so I can't really use getSelectedItem(). I wish I could.
The problem is, if I try to select something from the pulldown, and THEN use the editor, the selectedIndex() remains set.
How can I clear the combobox selectedIndex when I have a mouse event for the textfield? I can't find a way to get the combobox from the textfield.
I don't know if it's relevant but I also tie the text to the box via TextFields.bindAutoCompletion(cb.getEditor(), cb.getItems()));


Solution

  • From the ComboBox documentation:

    Because a ComboBox can be editable, and the default means of allowing user input is via a TextField, a string converter property is provided to allow for developers to specify how to translate a users string into an object of type T, such that the value property may contain it. By default the converter simply returns the String input as the user typed it, which therefore assumes that the type of the editable ComboBox is String. If a different type is specified and the ComboBox is to be editable, it is necessary to specify a custom StringConverter.

    (my emphasis).

    Therefore, you need to provide a converter for your ComboBox that defines how to convert the string the user typed in the combo box editor into an object of the correct type, and conversely how to convert an object of that type into a string to display in the text field.

    Once you have done that, the correct way to retrieve the value from the combo box is with

    cb.getValue();