从枚举填充JavaFX组合框或ChoiceBox
有没有办法用枚举的所有枚举填充JavaFX从枚举填充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) {
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;
}
}