"No select item" on JavaFX combobox?


What is the correct way to put an item which value is null, inside a ComboBox? I tried using myComboBox.getItems().add(null);, and it works, but whenever the user selects this value on the combo box, an exception is thrown on the console:

Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException
    at com.sun.javafx.scene.control.ReadOnlyUnbackedObservableList.subList(ReadOnlyUnbackedObservableList.java:136)

So i think maybe this is not the correct way of doing that. Any clues?

9/16/2014 7:53:46 PM

Accepted Answer

In my experience, this is a problem introduced in Java 8u20. In Java 8u05 and 8u11, as well as JavaFX 2.x, you could add null to the list of items, and selecting this item behaved as expected. In Java 8u20 you will get a java.lang.IndexOutOfBoundsException whenever selecting the null value.

Benjamin Gale: you will have to use Java 8u20, select an item in the ComboBox, and then select the null value to see the issue.

At the current time, the best option seems to be to create a special null-object and label it appropriately, as already mentioned.

Alternatively, if you can get by with using a ChoiceBox instead, I think you will find that it works the way you want.

9/17/2014 10:33:10 AM

I think it must be something with your code that you are not showing us as the SSCCE below works fine and doesn't throw any exceptions.

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class NullComboBoxApp extends Application {

    public void start(Stage primaryStage) {

        ComboBox<String> cb = new ComboBox<>(FXCollections.observableArrayList(
                "Option 1",
                "Option 2",
                "Option 3"


        StackPane root = new StackPane();

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Null ComboBox Example");

    public static void main(String[] args) {

Although this actually works, quite why you'd want your users to be able to select null is beyond me...is this actually the behaviour you want? I suspect you really want to be able to clear the current selection, something like:


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow