我确信有一种方法可以做到这一点,但似乎还不能完全做到。
我正在开发一个程序,它有一个用枚举填充的组合框。我需要获取选定的值并将其传递给setter方法,该方法当前接受一个字符串作为参数。
我认为它的工作原理是这样的:用户选择枚举值,程序计算出枚举值在枚举列表中的值,然后如果可能的话,只需调用一个toString并将其传递给setter。
我可能离得太远了,但任何帮助都是非常感谢的!
我已经试过String system = play.getSelectedItem().toString():
和String system = (String) play.getSelectedItem(); gGame.setPlayer(system);
了
发布于 2013-07-19 02:51:41
如何在JComboBox
中使用enum
的示例
//Definition of the enum
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;
}
}
//Assigning values of enum to 'play' JComboBox
play.setModel(new DefaultComboBoxModel(ItemType.values()));
//Reading the value of JComboBox
ItemType selectedType = (ItemType)play.getSelectedItem();
gGame.setPlayer(selectedType); //toString is overridden, so it will assign the appropriate text value of the enum
https://stackoverflow.com/questions/17736876
复制