I would like to populate a java.swing JComboBox
with values from an Enum
.
e.g.
public enum Mood { HAPPY, SAD, AWESOME; }
and have these three values populate a readonly JComboBox
.
Thanks!
try:
new JComboBox(Mood.values());
If you don't want to (or can't) change initialization with default constructor, then you can use setModel()
method:
JComboBox<Mood> comboBox = new JComboBox<>();
comboBox.setModel(new DefaultComboBoxModel<>(Mood.values()));
The solution proposed by @Pierre is good. Usually you use a DefaultComboBoxModel or a ComboBoxModel or bindings to the ComboBoxModel for more complex stuff.
By default a JComboBox is not editable.
This can also be achieved using only the default constructor and without using setModel()
method:
JComboBox<Mood> comboBox_mood = new JComboBox<>();