paw_rd
paw_rd

Reputation: 47

ChoiceBox in JavaFX - default title

I try to specify for the choicebox a "title". I tried to set the title as one of the options and set it to default. But I don't want the first option (which is the title) to appear in the list of options.

Here's the code I used:

ChoiceBox<String> choiceBox = new ChoiceBox<String>();
choiceBox.getItems().addAll("How old are you?", "10-20", "20-30", "30-40");
choiceBox.setId("choiceBox");
choiceBox.getSelectionModel().select(0);

And here is the result:

The result of the code

In the documentation I found this, but I couldn't figure out how to specify the selected item to be something that is not in the options list

ChoiceBox (JavaFX 11)

By default, the ChoiceBox has no item selected unless otherwise specified. Although the ChoiceBox will only allow a user to select from the predefined list, it is possible for the developer to specify the selected item to be something other than what is available in the predefined list. This is required for several important use cases.

Upvotes: 1

Views: 1152

Answers (1)

Miss Chanandler Bong
Miss Chanandler Bong

Reputation: 4258

ChoiceBoxSkin<T> shows the value of the selected item in a Label. Unfortunately, this label is private. If you have a reason to not use ComboBox<T>, here is a workaround:

ChoiceBox<String> choiceBox = new ChoiceBox<>();
choiceBox.getItems().addAll("10-20", "20-30", "30-40");
Platform.runLater(() -> {
    SkinBase<ChoiceBox<String>> skin = (SkinBase<ChoiceBox<String>>) choiceBox.getSkin();
    // children contain only "Label label" and "StackPane openButton"
    for (Node child : skin.getChildren()) {
        if (child instanceof Label) {
            Label label = (Label) child;
            if (label.getText().isEmpty()) {
                label.setText("How old are you?");
            }
            return;
        }
    }
});

Result:

Result

Upvotes: 2

Related Questions