JavaFx:如何从它的文本字段中获取组合框对象?

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

我有一个组合框 (cb)。当有人点击相关的文本字段时,我想清除它。我用

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

结果在cb.getEditor().getText() 到目前为止一切顺利。
如果我通过下拉而不是键入来填充框,结果在 cb.getSelectionModel().getSelectedIndex();
中 那也好。组合框填充了一个对象,而不是一个字符串,所以我不能真正使用 getSelectedItem()。我希望我能。
问题是,如果我尝试从下拉列表中 select 某些内容,然后使用编辑器,selectedIndex() 将保持设置。
当文本字段有鼠标事件时,如何清除组合框 selectedIndex?我找不到从文本字段获取组合框的方法。
我不知道它是否相关,但我还通过 TextFields.bindAutoCompletion(cb.getEditor(), cb.getItems()));

将文本绑定到方框

来自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.

(我的重点)。

因此,您需要为您的 ComboBox 提供一个转换器,定义如何将用户在组合框编辑器中键入的字符串转换为正确类型的对象,反之如何将对象转换为正确类型的对象将该类型转换为字符串以显示在文本字段中。

完成后,从组合框中检索值的正确方法是

cb.getValue();