JComboBox 填充枚举变量值

JComboBox fill with enum variable value

我有一个 JComboBox 是我用这种方式制作的,使用 enum 作为其值:

JComboBox<StudyGrade> maxLevelOfStudiesCombo = new JComboBox<StudyGrade>(StudyGrade.values());

enum 看起来像这样:

public enum StudyGrade {
    ELEMENTARY ("Primaria"),
    MIDDLE ("Secundaria"),
    MIDDLE_HIGH ("Preparatoria"),
    HIGH ("Universidad"),
    MASTERS ("Maestría / Posgrado"),
    DOCTORATE ("Doctorado"),
    POST_DOCTORATE ("Post Doctorado");

    private String studies;

    private StudyGrade(String studies) {
        this.studies = studies;
    }

    public String getStudies() {
        return studies;
    }

    public void setStudies(String studies) {
        this.studies = studies;
    }

    @Override
    public String toString() {
        return studies;
    }
}

如您所见,我正在覆盖 toString() 方法,因此我可以显示 studies 值而不是 enum 值...

但是我只想在 JComboBox 中显示 studies 值,而不是每次使用 StudyGrade 枚举时。

我将如何更改代码,所以每当我使用类似的东西时:

System.out.println(StudyGrade.HIGH);

我打印的是 HIGH 而不是 Universidad,但不是 JComboBox?

I'm overriding the toString() method, so I can have the studies values shown instead of the enum ones...

我以前从未使用过枚举,但我假设您可以像添加到组合框的任何自定义对象一样使用它,因此您应该能够使用自定义渲染器,以便您可以控制组合显示哪些数据盒子.

查看 Combo Box With Custom Renderer 了解更多信息和帮助 class。

您可以将 toString 覆盖删除为 the default toString for an enum is to return the name of the enum element

并且您可以只使用一个简单的 for 循环来遍历枚举中的值并将其添加到字符串数组中。然后,您需要将该数组作为 JComboBox 的参数传递,它应该是 gold。

它的代码看起来应该有点像这样:

//get all study grades
StudyGrade[] temp = StudyGrade.values(); 

//create a string array of same length as the array
String[] str = new String[temp.length];

//append all the studies value to the string array
for(int i = 0; i< temp.length; i++){
  str[i] = temp[i].getStudies();
  System.out.println(temp[i]);//debug
}

System.out.println("---------------------");//debug
for(String s : str){//debug
  System.out.println(s);//debug
}//debug

//pass it
JComboBox<StudyGrade> maxLevelOfStudiesCombo = new JComboBox<StudyGrade>(StudyGrade.values());

这是我在repl.it

上做的一个例子

https://repl.it/GH28/1

您希望扩展枚举,但那是不可能的。这意味着您的要求有问题。

呈现在 UI 组件中完成,处理数据呈现不是枚举的职责。您应该让 UI 组件以您喜欢的方式呈现枚举,而不是试图让枚举了解它的使用位置。由于您是 Swing 狂热者,您应该知道如何做到这一点,例如:

maxLevelOfStudiesCombo.setRenderer(new DefaultListCellRenderer() {
    @Override
    public Component getListCellRendererComponent(JList<?> jList, Object o, int i, boolean b, boolean b1) {
        Component rendererComponent = super.getListCellRendererComponent(jList, o, i, b, b1);
        setText(o instanceof StudyGrade ? ((StudyGrade) o).getStudies() : o.toString());
        return rendererComponent;
    }
});

就是这样。