mhansen
mhansen

Reputation: 1141

Populating Swing JComboBox from Enum

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

Answers (5)

Troyseph
Troyseph

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

M. Hamdi
M. Hamdi

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

user355491
user355491

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

John Doe
John Doe

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

Pierre
Pierre

Reputation: 35246

try:

new JComboBox(Mood.values());

Upvotes: 49

Related Questions