从枚举填充 JavaFX ComboBox 或 ChoiceBox [英] Populating JavaFX ComboBox or ChoiceBox from enum

查看:27
本文介绍了从枚举填充 JavaFX ComboBox 或 ChoiceBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法用枚举的所有枚举填充 JavaFX ComboBoxChoiceBox ?

Is there a way to populate a JavaFX ComboBox or ChoiceBox with all enumerations of a enum ?

这是我尝试过的:

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 :

In a another class, I'm trying to populate a ComboBox :

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

但我收到一个错误:不兼容的类型:Status[] 无法转换为 ObservableList

我显然在使用 ChoiceBox 时遇到了同样的问题.

I obviously get the same problem with a ChoiceBox.

推荐答案

如果 setItems 需要一个 ObservableList,那么你必须给它一个而不是一个数组.

If setItems requires an ObservableList, then you have to give it one instead of an array.

试试这个:

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

James_D(见评论)的解决方案是首选:

The solution of James_D (see comment) is the preferred one:

cbxStatus.getItems().setAll(Status.values());

这篇关于从枚举填充 JavaFX ComboBox 或 ChoiceBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆