How to use JComboBox using Enum in a dialog box

I define the enumerations:

enum itemType {First, Second, Third};

public class Item

{

private itemType enmItemType;

...

}

How to use it in a dialog using JComboBox? This means that inside the dialog box the user will have a combo box (First, Second, Third). Also, is it better to use some kind of identifier for each numerator? (Integer)

thanks.

+7
java enums jcombobox dialog
source share
3 answers
JComboBox combo = new JComboBox(itemType.values()); 
+8
source share

This is the approach I used:

 enum ItemType { First("First choice"), Second("Second choice"), Third("Final choice"); private final String display; private ItemType(String s) { display = s; } @Override public String toString() { return display; } } JComboBox jComboBox = new JComboBox(); jComboBox.setModel(new DefaultComboBoxModel(ItemType.values())); 

Overriding the toString method allows you to provide display text that represents meaningful options to the user.

Note. I also changed itemType to itemType , as type names should always have a top cap.

+21
source share

Assuming you know how to encode a dialog using JComboBox, follow these steps to load Enum values ​​into a combo box:

 enum ItemType {First, Second, Third}; JComboBox myEnumCombo = new JComboBox(); myEnumCombo.setModel(new DefaultComboBoxModel(ItemType.values()); 

Then, to get the value as enum, you could do

 (ItemType)myEnumCombo.getSelectedItem(); 

There is no need to assign identifiers for enumerations unless your application logic needs to have a meaningful identifier. Enum itself already has a unique identification system.

+3
source share

All Articles