1

I want to have an editable ComboBox that contains items of some type (e.g. integers), where I can add and delete items, allow the user to edit existing items, and allow for duplicate items.

The problem is that whenever the user edits an existing item, and changes its value to a value of an item already present in the list, the editor (textfield) causes the selection model to select the item already present in the list instead of modifying the edited item.

I tried circumventing this by creating a wrapper class that contains the item and has an unique index. However, this causes problems in StringConverter.fromString because I have to create a new wrapper every time it converts.

An easy solution I think would be to stop the editor from searching through the items whenever an edit is made, so that the selection model does not change.

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);
    }
}
  • most of the time, duplicates don't make sense in an ui. Or the other way round: most application data are more complex and at least not identical to each other, so practically, the problem doesn't arise most of the time. Note the _most_ everywhere, corner cases exist :) So what are the real data in your case, why do you need real duplicates in the list? – kleopatra Sep 26 '20 at 10:41
  • all that said: your _easy solution_ is none, the _wrapper_ sounds like a reasonable way to go (why is that a problem? too many ids?). Another might be to use a TextFormatter on the combo's editor, such that you do the conversion only on actual edits. Anyway, not enough details to answer, please provide a [mcve] that's nearer to your real problem. – kleopatra Sep 26 '20 at 10:48

0 Answers0