ComboBox FXML默认值

Per*_*eel 16 java combobox javafx javafx-2 fxml

如何在ComboBox使用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>
Run Code Online (Sandbox Code Playgroud)

我希望NVT默认选中.我尝试添加selected="selected",但似乎没有找到正确的语法.

是否可以使用Scene Builder编辑列出的项目?我似乎找不到它.

小智 41

用这个:

<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>
Run Code Online (Sandbox Code Playgroud)

  • `<ComboBox value ="NVT">`也有效,看起来更干净. (7认同)

Teo*_*ali 8

我不认为它在FXML中是可能的.您需要在组件的初始化中,在控制器中执行此操作,例如使用以下行cbo_Bacteriologie_Aesculine.getSelectionModel().setSelectedIndex(1);来选择元素Bezig.

但如果您在FXML中找到了一种方法,我感兴趣.

编辑:在FXML中是可能的.您可以在Guedolino的答案(/sf/answers/1010546001/)中看到它,它应该成为这个问题的正确答案.


The*_*Cat 6

我用第一个建议的方法得到了一个奇怪的错误

setSelectedItem(T)在SelectionModel中具有受保护的访问权限,其中T是一个类型变量:T扩展在类SelectionModel中声明的Object

为了我

getSelectionModel().select("NVT");
Run Code Online (Sandbox Code Playgroud)

像魅力一样工作.