gpt4 book ai didi

java - 使用枚举组合框中的值作为 setter 的参数

转载 作者:行者123 更新时间:2023-12-01 14:19:36 25 4
gpt4 key购买 nike

我确信有一种方法可以做到这一点,但似乎不太明白。

我正在开发一个程序,该程序有一个填充有枚举的组合框。我需要获取选定的值并将其传递给当前采用字符串作为参数的 setter 方法。

我认为它会起到类似的作用;用户选择枚举值,程序找出枚举列表中该枚举的值,然后如果可能,只需调用 toString 并将其传递到 setter 中。

我可能还很遥远,但是非常感谢您的帮助!

我尝试过String system = (String) play.getSelectedItem(); gGame.setPlayer(系统);以及String system = play.getSelectedItem().toString():

最佳答案

如何在 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

关于java - 使用枚举组合框中的值作为 setter 的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17736876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com