firestruq
firestruq

Reputation: 739

how to use JComboBox using Enum in Dialog Box

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.

Upvotes: 7

Views: 22744

Answers (3)

Devon_C_Miller
Devon_C_Miller

Reputation: 16518

This is the approach I have 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 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.

Upvotes: 23

ColinD
ColinD

Reputation: 110046

JComboBox combo = new JComboBox(itemType.values());

Upvotes: 10

ring bearer
ring bearer

Reputation: 20783

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.

Upvotes: 4

Related Questions