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.
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.
精彩评论