Skip to main content

ComboBoxes

Geoffrey Hunter
mbedded.ninja Author

Associating With An Enum

One of the tidiest ways of populating a JavaFX ComboBox is to associate it with an enumeration. The enumeration defines the objects you can select from in the ComboBox, as well as how to display these objects (their String representations).

First, we need to create an enum:

public enum MyEnum {

OPTION_1("Option 1"),
OPTION_2("Option 2"),
OPTION_3("Option 3"),
;

private String label;

MyEnum(String label) {
this.label = label;
}

@Override
public String toString() {
return label;
}

}

Then, to populate the ComboBox, just type:

myComboBox.getItems().setAll(MyEnum.values());

To select an item from code (useful for say, setting the default value of the ComboBox), type:

myComboBox.getSelectionModel().select(MyEnum.OPTION_1);

Notice we are now dealing with objects, rather than having to parse strings!