首页 > 解决方案 > JavaFX可编辑组合框不允许重复项

问题描述

我想要一个可编辑的组合框,其中包含某种类型的项目(例如整数),我可以在其中添加和删除项目,允许用户编辑现有项目,并允许重复项目。

问题在于,每当用户编辑现有项目并将其值更改为列表中已存在的项目的值时,编辑器(文本字段)会导致选择模型选择列表中已存在的项目,而不是修改编辑的项目。

我尝试通过创建一个包含该项目并具有唯一索引的包装类来规避这一点。但是,这会导致 StringConverter.fromString 出现问题,因为每次转换时我都必须创建一个新包装器。

我认为一个简单的解决方案是在进行编辑时阻止编辑器搜索项目,以便选择模型不会改变。

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;

import java.util.Arrays;

public class ComboBoxTest extends Application {

    private final ComboBox<Integer> comboBox = new ComboBox<>();

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

    @Override
    public void start(Stage primaryStage) {
        final Group root = new Group();
        root.getChildren().add(comboBox);

        final Scene scene = new Scene(root, 200, 200);
        primaryStage.setScene(scene);
        primaryStage.show();

        comboBox.getItems().addAll(Arrays.asList(1, 2, 3, 4));
        comboBox.setConverter(
            new StringConverter<Integer>() {
                @Override
                public String toString(Integer integer) {
                    return integer == null ? "" : String.valueOf(integer);
                }

                @Override
                public Integer fromString(String s) {
                    return Integer.parseInt(s);
                }
            });
        comboBox.setPromptText("select value");
        comboBox.setEditable(true);
    }
}

标签: javajavafxcomboboxtextfieldselectionmodel

解决方案


推荐阅读