JavaFX & FXML: how do I set the default selected item in a ChoiceBox in FXML?


Question

I have the following FXML:

<ChoiceBox>
    <items>
        <FXCollections fx:factory="observableArrayList">
            <String fx:value="2 minutes" />
            <String fx:value="5 minutes" />
            <String fx:value="15 minutes" />
        </FXCollections>
    </items>
</ChoiceBox>

But in the GUI it just shows a ChoiceBox with a default of nothing. I would like the first element in the list to be the default, and for a choice of "null" or nothing to be prohibited.

How do I accomplish this?

1
11
8/15/2013 1:28:05 AM

Accepted Answer

I added the value attribute to the ChoiceBox tag, and that worked.

<ChoiceBox value="2 minutes">
    <items>
        <FXCollections fx:factory="observableArrayList">
            <String fx:value="2 minutes" />
            <String fx:value="5 minutes" />
            <String fx:value="15 minutes" />
        </FXCollections>
    </items>
</ChoiceBox>
13
8/15/2013 3:27:09 AM

@Groostav: In case we programmatically "know" the value that should appear as selected (for example, we landed in an edit form), we can do the following:

1) Add a new item with index 0 (that is, the element we need to show as selected):

myChoiceBox.getItems().add(0, ItemObtainedProgrammatically);

2) Show the item as selected (since we already know it's at position 0):

myChoiceBox.getSelectionModel().select(0);

Probably this qualifies as a dirty hack, but it works. The con: You have the same item twice in your choicebox


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