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

3

17

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?

Jounce answered 15/8, 2013 at 1:28 Comment(0)
J
19

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>
Jounce answered 15/8, 2013 at 3:27 Comment(1)
in the name of avoiding hard-coded string values, is there a way I can reference a field or method on the controller to get this value? I cant use fx:constant because it would only look for fields on the String class, and I cant (really) use the binding syntax because that would leave the property bound.Argolis
H
1

First, you should import your needed value model, like Crowell answer, you should import like this in your fxml header:

<?import javafx.collections.*?>

Second, if you want's import your own model, import it first and then like this:

<?import com.zzg.mybatis.generator.model.*?>
....

<ChoiceBox layoutX="24.0" layoutY="14.0" prefWidth="150.0">
      <items>
            <FXCollections fx:factory="observableArrayList">
                  <DatabaseDTO name="MySQL" value="1"></DatabaseDTO>
                  <DatabaseDTO name="Oracle" value="2"></DatabaseDTO>
            </FXCollections>
      </items>
</ChoiceBox>
Hermelindahermeneutic answered 9/5, 2016 at 0:5 Comment(2)
This does not answer the question at all! The question was how to set a default value and not how to import and include custom models of any kind.Swayne
<?import javafx.collections.*?> this part saved my timeWellturned
R
1

@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

Radiobiology answered 28/11, 2018 at 20:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.