A Swing JComboBox for Enums
February 10th, 2009
Here is a quick and dirty combo box class I wrote the other day. It displays all of the values from a Java enum.
public class EnumCombo<E extends Enum<E>> extends JComboBox {
private final Class<E> enumClass;
public EnumCombo(Class<E> enumClass) {
this.enumClass = enumClass;
for (E e : enumClass.getEnumConstants()) {
addItem(e);
}
}
public E getSelectedItem() {
return enumClass.cast(super.getSelectedItem());
}
}
Using the combo box looks like this:
EnumCombo<Status> statusCombo = new EnumCombo<Status>(Status.class);
You’ll probably want to override toString() in the enum to display friendly values in the combo box.
or simply use EnumComboBoxModel ?