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.
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.
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.
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.
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.
JComboBox combo = new JComboBox(itemType.values());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With