Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从枚举填充JavaFX组合框或ChoiceBox_Java_Combobox_Enums_Javafx - Fatal编程技术网

从枚举填充JavaFX组合框或ChoiceBox

从枚举填充JavaFX组合框或ChoiceBox,java,combobox,enums,javafx,Java,Combobox,Enums,Javafx,有没有办法用枚举的所有枚举填充JavaFXComboBox或ChoiceBox 以下是我尝试过的: public class Test { public enum Status { ENABLED("enabled"), DISABLED("disabled"), UNDEFINED("undefined"); private String label; Status(String label) {

有没有办法用枚举的所有枚举填充JavaFX
ComboBox
ChoiceBox

以下是我尝试过的:

public class Test {

    public enum Status {
        ENABLED("enabled"),
        DISABLED("disabled"),
        UNDEFINED("undefined");

        private String label;

        Status(String label) {
            this.label = label;
        }

        public String toString() {
            return label;
        }
    }
}
在另一个类中,我试图填充一个组合框:

    ComboBox<Test.Status> cbxStatus = new ComboBox<>();
    cbxStatus.setItems(Test.Status.values());
ComboBox cbxStatus=new ComboBox();
cbxStatus.setItems(Test.Status.values());
但是我得到一个错误:
不兼容的类型:Status[]无法转换为observebleList


显然,我对
选择框

也有同样的问题。如果setItems需要一个observeList,那么您必须给它一个而不是数组

试试这个:

ComboBox<Status> cbxStatus = new ComboBox<>();
cbxStatus.setItems( FXCollections.observableArrayList( Status.values()));

我用FXML来做这个。我的枚举有一个构造函数

<ComboBox GridPane.rowIndex="0" GridPane.columnIndex="1">
        <items>
            <FXCollections fx:factory="observableArrayList">
                <Type fx:value="ABC"/>
                <Type fx:value="DEF"/>
                <Type fx:value="GHI"/>
            </FXCollections>
        </items>
    </ComboBox>

或者
cbxStatus.getItems().setAll(Status.values())哦,是的,那个更好:DJames_D解决方案是我选择的!有什么方法可以从FXML中实现它吗?这没有多大区别,但是
cbxStatus.getItems().setAll(Arrays.asList(Status.values())
将避免出现“非varargs调用varags方法”的警告。一个可能更优雅的解决方案是使用
fx:constant
,因此它直接引用枚举值,而不是依赖
方法的静态
值。某些编辑器甚至可以在使用
fx:constant
时提供补全。
<ComboBox GridPane.rowIndex="0" GridPane.columnIndex="1">
        <items>
            <FXCollections fx:factory="observableArrayList">
                <Type fx:value="ABC"/>
                <Type fx:value="DEF"/>
                <Type fx:value="GHI"/>
            </FXCollections>
        </items>
    </ComboBox>
public enum Type {

    ABC("abc"),DEF("def"),GHI("ghi");

    private String name;

    private Type(String theType) {
        this.name = theType;
    }

}