Reputation: 1141
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!
Upvotes: 37
Views: 44373
Reputation: 5138
You could extend the JComboBox class, and use some reflection to extract the values from an enum type automatically to populate a JComboBox
public class EnumComboBox<EnumType extends Enum<EnumType>> extends JComboBox<EnumType> {
// We still need a runtime type parameter due to type erasure
public EnumComboBox(Class<EnumType> enumClass) {
_enumClass = enumClass;
for (EnumType value : enumClass.getEnumConstants()) {
this.addItem(value);
}
}
@SuppressWarnings("unchecked")
public EnumType getSelectedEnumValue() {
return (EnumType) getSelectedItem();
}
public void setSelectedEnumValue(EnumType value) {
setSelectedItem(value);
}
public Class<EnumType> getEnumClass() {
return _enumClass;
}
private Class<EnumType> _enumClass;
}
Upvotes: 1
Reputation: 1
This can also be achieved using only the default constructor and without using setModel()
method:
JComboBox<Mood> comboBox_mood = new JComboBox<>();
Upvotes: 0
Reputation:
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()));
Upvotes: 24
Reputation: 867
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.
Upvotes: 0