If you are using Swing and not command prompt or web form, you can actually pass enum instances into a JComboBox. When the user makes a selection, you will get the Enum instance directly, without having to translate between String and Enum. This has the advantage that you don't need to worry about changing Enum names or upper/lower case errors.
Example:
public class Enums
{
public enum Days{
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
public String toString() {
//return user-friendly name, or whatever else you want.
//for complex rendering, you need to use cell renderer for the combo box
return name().substring(0,1) + name().toLowerCase().substring(1, name().length());
};
}
public static void main(String[] args) {
JFrame frame = new JFrame("Enum test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JComboBox<Days> combo = new JComboBox<>(Days.values());
combo.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED){
Days selected = combo.getItemAt(combo.getSelectedIndex());
System.out.println(selected);
}
}
});
frame.add(combo);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
No type casting, no string matching. Super-safe.