Search code examples
javafxenumscomboboxfxml

Bind enum values to Combox in FXML


I have a JavaFX application, and I'm trying to map all the values of an enum to a Combobox from FXML.

Something like the below works just fine, however, I'm looking for a more generic solution, where I don't need to list all possible values of the enum manually.

<ComboBox>
     <items>
         <FXCollections fx:factory="observableArrayList">
              <MyEnum fx:constant="VALUE1"/>
              <MyEnum fx:constant="VALUE2"/>
          </FXCollections>
     </items>
</ComboBox>

Solution

  • This is not possible without some additional code, since there's no way of adding multiple objects to a list at once and initializing the list isn't possible either.

    You could create a helper class providing static getter/setter methods though. This method could use reflection to add the enum constants:

    public class EnumUtil {
        /* getter needed for FXMLLoader */
        public static Class<?> getEnumClass(ObservableList list) {
            return list.isEmpty() ? null : list.get(0).getClass();
        }
    
        public static <T extends Enum<T>> void setEnumClass(ObservableList<? super T> list, Class<T> enumClass) {
            if (!enumClass.isEnum()) {
                throw new IllegalArgumentException(enumClass.getName() + " is not a enum type");
            }
            list.addAll(enumClass.getEnumConstants());
        }
    }
    

    fxml

    <ComboBox>
         <items>
             <!-- fill combobox with constants from KeyCode -->
             <FXCollections fx:factory="observableArrayList" EnumUtil.enumClass="javafx.scene.input.KeyCode"/>
         </items>
    </ComboBox>