How to set context menu width to match choice box

1.6k Views Asked by At

I created ChoiceBox using scene builder 2.0 and attached to IntelliJ Idea and add below code to add item to ChoiceBox in Main class

ChoiceBox genderBox = (ChoiceBox) scene.lookup("#gender");
genderBox.setItems(FXCollections.observableArrayList("Boy", "Girl"));
genderBox.getSelectionModel().select(0); 

Choice box code from FXML is as below

<ChoiceBox id="gender" prefHeight="16.0" prefWidth="150.0" GridPane.columnIndex="1" GridPane.rowIndex="11">
           <GridPane.margin>
              <Insets left="10.0" />
           </GridPane.margin>
</ChoiceBox>

Anyway, when running the Main class I see the choice box as below. choice box width is not matched with context menu(popup) width.

gender choice box

How to set a width to the context menu?

EDIT

Anyway setting width to the context menu in combo box is working fine. So I moved with combo box. see example fxml.

1

There are 1 best solutions below

0
On

First, set width of the ChoiceBox itself...

<ChoiceBox prefWidth="150">
    ...
</ChoiceBox>

Then, set width of the popup list via CSS...

.choice-box .menu-item > .label {
    -fx-pref-width: 100;
}

note: the box is about 50px wider than the list because of the drop-down button.