从枚举填充 JavaFX ComboBox 或 ChoiceBox
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27801119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Populating JavaFX ComboBox or ChoiceBox from enum
提问by Jér?me
Is there a way to populate a JavaFX ComboBox
or ChoiceBox
with all enumerations of a enum ?
有没有办法填充 JavaFXComboBox
或ChoiceBox
使用 enum 的所有枚举?
Here is what I tried :
这是我尝试过的:
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;
}
}
}
In a another class, I'm trying to populate a ComboBox
:
在另一堂课中,我试图填充一个ComboBox
:
ComboBox<Test.Status> cbxStatus = new ComboBox<>();
cbxStatus.setItems(Test.Status.values());
But I get an error : incompatible types: Status[] cannot be converted to ObservableList<Status>
但我收到一个错误: incompatible types: Status[] cannot be converted to ObservableList<Status>
I obviously get the same problem with a ChoiceBox
.
我显然遇到了同样的问题ChoiceBox
。
采纳答案by Roland
If setItems requires an ObservableList, then you have to give it one instead of an array.
如果 setItems 需要一个 ObservableList,那么你必须给它一个而不是一个数组。
Try this:
尝试这个:
ComboBox<Status> cbxStatus = new ComboBox<>();
cbxStatus.setItems( FXCollections.observableArrayList( Status.values()));
Edit: The solution of James_D (see comment) is the preferred one:
编辑:James_D(见评论)的解决方案是首选:
cbxStatus.getItems().setAll(Status.values());
回答by rizcan
I used FXML for this. My enum has a constructor
我为此使用了 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>
public enum Type {
ABC("abc"),DEF("def"),GHI("ghi");
private String name;
private Type(String theType) {
this.name = theType;
}
}