Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 467
mhansen Avatar asked Sep 22 '09 09:09

mhansen


People also ask

What is jcombobox in Java Swing?

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 .

How do I bind a combobox from an enum?

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.

What is setmaximumrowcount in jcombobox?

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.

What is setselectedindex in jcombobox?

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.


2 Answers

try:

new JComboBox(Mood.values()); 
like image 81
Pierre Avatar answered Sep 22 '22 02:09

Pierre


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())); 
like image 40
tellnobody1 Avatar answered Sep 21 '22 02:09

tellnobody1