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

前端 未结 3 814
走了就别回头了
走了就别回头了 2021-01-04 04:17

I have the following FXML:


    
        
            

        
3条回答
  •  孤城傲影
    2021-01-04 04:59

    @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

提交回复
热议问题