views:

171

answers:

3

Hi,

I define enums:

enum itemType {First, Second, Third};

public class Item

{

private itemType enmItemType;

...

}

How do I use it inside Dialog box using JComboBox? Means, inside the dialog box, the user will have combo box with (First, Second, Third). Also, is it better to use some sort of ID to each numerator? (Integer)

thanks.

+1  A: 

Assuming you know how to code a dialog box with a JComboBox, following is something you can do to load Enum values on to a combo box:

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

Then to get value as enum you could do

(ItemType)myEnumCombo.getSelectedItem();

There is no need to assign IDs to enums unless your application logic badly needs to have some meaningful ID assigned. The enum itself already has a unique ID system.

ring bearer
+1  A: 

This is the approach I have used:

enum ItemType {
    First("First choice"), Second("Second choice"), Third("Final choice");
    private final String display;
    private ItenType(String s) {
        display = s;
    }
    @Override
    String toString() {
        return display;
    }
}

jComboBox.setModel(new DefaultComboBoxModel(ItemType.values()));

Overriding the toString method allow you to provide display text that presents the user with meaningful choices.

Note: I've also changed itemType to ItemType as type names should always have a leading cap.

Devon_C_Miller
+1  A: 
JComboBox combo = new JComboBox(itemType.values());
ColinD