简体   繁体   English

如何在Java中的Jcombobox中使用浮点枚举

[英]How do I use float enums with a Jcombobox in Java

I have an enum class that uses floats for its values eg 我有一个枚举类,其值使用浮点数

public enum Size {

    SMALL(10.50f),MEDIUM(12.35f),LARGE(15.90f);

    private float value;

    Size(float value){ 
        this.value = value;
    }
    public float getValue(){
        return this.value;
    }
}

I want to use this enum to 'generate' the list that will be used for a Jcombobox where the user will select one of the sizes. 我想使用此枚举“生成”将用于Jcombobox的列表,用户将在其中选择大小之一。

ddSize.setModel((Size.values()));

I'm trying to use the code above, however I get the following error: 我正在尝试使用上面的代码,但是出现以下错误:

error: incompatible types: Size[] cannot be converted to ComboBoxModel<String>
        ddSize.setModel((Size.values()));

I need a way for me to be able to use the float enums without getting this error, if possible. 如果可能,我需要一种方法来使用浮点枚举而不出现此错误。

setModel took a ComboBoxModel<E> , so you can use DefaultComboBoxModel to fill the JComboBox like so : setModelComboBoxModel<E> ,因此您可以使用DefaultComboBoxModel来填充JComboBox如下所示:

ddSize.setModel(new DefaultComboBoxModel(Size.values()));

to make sure it works : 确保它有效:

IntStream.range(0, ddSize.getItemCount())
        .forEach(index -> System.out.println(ddSize.getItemAt(index)));

Outputs 产出

SMALL
MEDIUM
LARGE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM