38

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!

JosEduSol
  • 5,268
  • 3
  • 23
  • 31
mhansen
  • 1,102
  • 1
  • 12
  • 18

4 Answers4

49

try:

new JComboBox(Mood.values());
Pierre
  • 34,472
  • 31
  • 113
  • 192
  • 2
    This will return the exact name of the enum value. If you want more UI friendly names, JComboBox will use overridden toString() methods. – Mr. Wrong Apr 16 '19 at 12:33
24

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()));
multitask landscape
  • 8,273
  • 3
  • 33
  • 31
  • 1
    Note [*Type Inference for Generic Instance Creation*](http://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html) and [generic model](http://docs.oracle.com/javase/7/docs/api/javax/swing/DefaultComboBoxModel.html), new in Java 7. – trashgod Feb 18 '12 at 16:15
1

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.

John Doe
  • 869
  • 5
  • 10
0

This can also be achieved using only the default constructor and without using setModel() method:

JComboBox<Mood> comboBox_mood = new JComboBox<>();
M. Hamdi
  • 1
  • 3