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);
}
}