首页 > 解决方案 > 使用鼠标选择值时,带有 ControlsFX 的 AutoComplete ComboBox 会触发自动完成

问题描述

我有一个简单ComboBox的,我使用 ControlsFX 来自动完成。除了一个恼人的缺陷外,这非常有效:当用户使用下拉菜单用鼠标选择一个项目时,自动完成窗口打开,本质上是向用户提供匹配的建议。

所需的行为是用鼠标选择一个值以完全关闭弹出窗口。

下面的代码将演示:

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import org.controlsfx.control.textfield.TextFields;

public class AutoCompleteComboBox extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

        // Simple Interface
        VBox root = new VBox(10);
        root.setAlignment(Pos.CENTER);
        root.setPadding(new Insets(10));

        // Create a standard ComboBox
        ComboBox<Person> comboBox = new ComboBox<>();

        // Sample items
        ObservableList<Person> people = FXCollections.observableArrayList();
        people.addAll(
                new Person("William", 34),
                new Person("Ashley", 12),
                new Person("Marvin", 63),
                new Person("Suresh", 18),
                new Person("Jackson", 24)
        );
        comboBox.setItems(people);

        // Add StringConverter
        comboBox.setConverter(new StringConverter<Person>() {
            @Override
            public String toString(Person person) {
                return (person == null ? null : person.getName());
            }

            @Override
            public Person fromString(String string) {
                for (Person person : comboBox.getItems()) {
                    if (person.getName().equalsIgnoreCase(string)) {
                        return person;
                    }
                }
                return null;
            }
        });

        // Make the ComboBox autocomplete using ControlsFX
        comboBox.setEditable(true);
        TextFields.bindAutoCompletion(comboBox.getEditor(), comboBox.getItems());

        root.getChildren().add(comboBox);

        // Show the stage
        primaryStage.setScene(new Scene(root));
        primaryStage.setTitle("Sample");
        primaryStage.show();
    }
}

class Person {
    private final String name;
    private final int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return name;
    }
}

因此,在编辑器中输入并使用键盘选择一个值可以正常工作。但是,如果您单击箭头以打开下拉菜单并以这种方式选择一个值,您会看到问题(它实质上会强制用户选择一个值两次)。

我将如何防止这种行为?

标签: javafxcontrolsfx

解决方案


推荐阅读