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!
Java Swing | JComboBox with examples. JComboBox is a part of Java Swing package. JComboBox inherits JComponent class . JComboBox shows a popup menu that shows a list and the user can select a option from that specified list . JComboBox can be editable or read- only depending on the choice of the programmer .
Populate (Bind) ComboBox from Enum in Windows Forms (WinForms) Application Inside the Form Load event, the values of the Enum are fetched into an Array and then a loop is executed over the Array items and one by one each item is added to a List collection of Key Value Pairs.
setMaximumRowCount (int count): sets the maximum number of rows the JComboBox displays. setEnabled (boolean b): enables the combo box so that items can be selected. removeItem (Object anObject) : removes an item from the item list. removeAllItems (): removes all items from the item list.
setSelectedIndex (int i): selects the element of JComboBox at index i. showPopup () :causes the combo box to display its popup window. setUI (ComboBoxUI ui): sets the L&F object that renders this component. setSelectedItem (Object a): sets the selected item in the combo box display area to the object in the argument.
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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With