在 FXML 中传递枚举
Pass Enum in FXML
我正在制作自定义 FXML 组件。我想要做的是将枚举传递给组件,以便它可以从枚举中检索所有值。这是自定义组件的片段:
public ChoiceBoxSetting(@NamedArg("values") Enum values) {
choiceBox.getItems().setAll(values.getDeclaringClass().getEnumConstants());
这是创建它的 FXML:
<ChoiceBoxSetting>
<values>
<MyCustomValues/>
</values>
</ChoiceBoxSetting>
这是 MyCustomValues
枚举:
public enum MyCustomValues {
HI, HELLO, ME
}
所以当我 运行 它时,我得到这个异常:
Caused by: javafx.fxml.LoadException: MyCustomValues is not a valid type.
我正在尝试传递枚举本身,不是枚举值之一,例如MyCustomValues.HI
。
名称对应于 class 名称的元素是 FXMLLoader
实例化 class 的指令;所以
<MyCustomValues/>
将导致 FXMLLoader
尝试调用 new MyCustomValues()
,当然它不能使用枚举类型。
理想情况下,您希望在此处传递实际的 Class
对象本身,但我看不出有什么方法可以在 FXML 中实例化 Class<?>
,我认为您能做的最好的事情是传递 class 的名称。例如:
package application;
import javafx.beans.NamedArg;
import javafx.scene.control.ChoiceBox;
public class EnumChoiceBox<E extends Enum<E>> extends ChoiceBox<E> {
public EnumChoiceBox(@NamedArg("enumType") String enumType) throws Exception {
Class<E> enumClass = (Class<E>) Class.forName(enumType);
getItems().setAll(enumClass.getEnumConstants());
}
}
然后你可以做:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.StackPane?>
<?import application.EnumChoiceBox?>
<StackPane xmlns:fx="http://javafx.com/fxml/1">
<EnumChoiceBox enumType="application.MyCustomValues"/>
</StackPane>
(将 application
替换为 MyCustomValues
的实际包名)。
我正在制作自定义 FXML 组件。我想要做的是将枚举传递给组件,以便它可以从枚举中检索所有值。这是自定义组件的片段:
public ChoiceBoxSetting(@NamedArg("values") Enum values) {
choiceBox.getItems().setAll(values.getDeclaringClass().getEnumConstants());
这是创建它的 FXML:
<ChoiceBoxSetting>
<values>
<MyCustomValues/>
</values>
</ChoiceBoxSetting>
这是 MyCustomValues
枚举:
public enum MyCustomValues {
HI, HELLO, ME
}
所以当我 运行 它时,我得到这个异常:
Caused by: javafx.fxml.LoadException: MyCustomValues is not a valid type.
我正在尝试传递枚举本身,不是枚举值之一,例如MyCustomValues.HI
。
名称对应于 class 名称的元素是 FXMLLoader
实例化 class 的指令;所以
<MyCustomValues/>
将导致 FXMLLoader
尝试调用 new MyCustomValues()
,当然它不能使用枚举类型。
理想情况下,您希望在此处传递实际的 Class
对象本身,但我看不出有什么方法可以在 FXML 中实例化 Class<?>
,我认为您能做的最好的事情是传递 class 的名称。例如:
package application;
import javafx.beans.NamedArg;
import javafx.scene.control.ChoiceBox;
public class EnumChoiceBox<E extends Enum<E>> extends ChoiceBox<E> {
public EnumChoiceBox(@NamedArg("enumType") String enumType) throws Exception {
Class<E> enumClass = (Class<E>) Class.forName(enumType);
getItems().setAll(enumClass.getEnumConstants());
}
}
然后你可以做:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.StackPane?>
<?import application.EnumChoiceBox?>
<StackPane xmlns:fx="http://javafx.com/fxml/1">
<EnumChoiceBox enumType="application.MyCustomValues"/>
</StackPane>
(将 application
替换为 MyCustomValues
的实际包名)。