JavaFX 2.0 Choice Box Issue. How to update a choiceBox, which represents a list of objects, when an object is updated?

后端 未结 3 453
独厮守ぢ
独厮守ぢ 2021-01-02 04:21

I have a choiceBox which represents a list objects. When the name representing one of those objects is changed by another bit of code the name in the drop down list for the

3条回答
  •  清酒与你
    2021-01-02 04:37

    I had the same issue in JavaFX 8 (with ComboBox too). I was able to get the same functionality by removing the item then adding a new one at the same location.

    Example:

    This gets selected item, creates a new item, then calls the replace method:

    Channel selected = channelChoiceBox.getSelectionModel().getSelectedItem();
    Channel newChan = new Channel("Example", "Channel");
    replaceChannel(newChan, selected);
    

    This replaces the selected channel with the new one, effectively editing it:

    private void replaceChannel(Channel newChan, Channel oldChan) {
        int i = channelChoiceBox.getItems().indexOf(oldChan);
        channelChoiceBox.getItems().remove(oldChan);
        channelChoiceBox.getItems().add(i, newChan);
        channelChoiceBox.setValue(newChan);
    }
    

    It's not ideal, but does the job.

    Disclaimer: I'm new to Java and programming in general.

提交回复
热议问题