Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 919
firestruq Avatar asked Apr 26 '10 16:04

firestruq


People also ask

How does JComboBox work?

Class JComboBox<E> A component that combines a button or editable field and a drop-down list. The user can select a value from the drop-down list, which appears at the user's request. If you make the combo box editable, then the combo box includes an editable field into which the user can type a value.

What is an enum Java?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

Which is the superclass for JComboBox?

Other methods you are most likely to invoke on a JComboBox object are those it inherits from its superclasses, such as setPreferredSize . See The JComponent API for tables of commonly used inherited methods.


3 Answers

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.

like image 196
Devon_C_Miller Avatar answered Oct 04 '22 20:10

Devon_C_Miller


JComboBox combo = new JComboBox(itemType.values());
like image 22
ColinD Avatar answered Oct 04 '22 20:10

ColinD


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.

like image 24
ring bearer Avatar answered Oct 04 '22 21:10

ring bearer