19

How can I set a default value in a ComboBox using FXML?

<ComboBox fx:id="cbo_Bacteriologie_Aesculine" prefHeight="21.0" prefWidth="105.0" GridPane.columnIndex="1" GridPane.rowIndex="0">
    <items>
        <FXCollections fx:factory="observableArrayList">
            <String fx:value="NVT" />
            <String fx:value="Bezig" />
            <String fx:value="Positief" />
            <String fx:value="Negatief" />
        </FXCollections>
    </items>
</ComboBox>

I want NVT to be selected by default. I tried adding selected="selected" and such but don't seem to find the right syntax.

Is it possible to edit the listed items using Scene Builder? I can't seem to find it.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Perneel
  • 3,317
  • 7
  • 45
  • 66

3 Answers3

50

Use this:

<ComboBox>
    <items>
        <FXCollections fx:factory="observableArrayList">
            <String fx:value="NVT" />
            <String fx:value="Bezig" />
            <String fx:value="Positief" />
            <String fx:value="Negatief" />
        </FXCollections>
    </items>
    <value>
        <String fx:value="NVT" />
    </value>
</ComboBox>
Guedolino
  • 566
  • 6
  • 2
8

I don't think it's possible in the FXML. You will need to do it in the initialization of the component, in the controller, for example using the following line cbo_Bacteriologie_Aesculine.getSelectionModel().setSelectedIndex(1); for selecting the element Bezig.

But if you find a way to do it in FXML, I am interested.

EDIT : It is possible in FXML. You can see it in Guedolino's answer (https://stackoverflow.com/a/14436371/1344424), which should become the right answer to this question.

Community
  • 1
  • 1
Teocali
  • 2,725
  • 2
  • 23
  • 39
  • 1
    okay I used the following code `cbo_Bacteriologie_Aesculine.getSelectionModel().selectFirst();` and it does the trick. I hope there will come support to handle this in FXML :) – Perneel Jul 28 '12 at 16:24
6

I got a strange error with the first suggested method

setSelectedItem(T) has protected access in SelectionModel where T is a type-variable: T extends Object declared in class SelectionModel

For me

getSelectionModel().select("NVT");

worked like a charm.

The Unfun Cat
  • 29,987
  • 31
  • 114
  • 156