Issue
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 aTextField
, a stringconverter
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 theconverter
simply returns theString
input as the user typed it, which therefore assumes that the type of the editableComboBox
isString
. If a different type is specified and theComboBox
is to be editable, it is necessary to specify a customStringConverter
.
(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();
Answered By - James_D
Answer Checked By - Clifford M. (JavaFixing Volunteer)