将自定义 class 识别为 fxml 标记

Getting a custom class to be recognized as an fxml tag

我有一个扩展 TextField 的自定义文本字段 PersistentPromptTextField,我希望能够将它添加到我的 .fxml 文件中。当我这样做并且 运行 它时,我得到一个错误列表,例如:

Caused by: java.lang.InstantiationException: gui.PersistentPromptTextField
at java.lang.Class.newInstance(Unknown Source)
at sun.reflect.misc.ReflectUtil.newInstance(Unknown Source)
... 75 more
Caused by: java.lang.NoSuchMethodException: gui.PersistentPromptTextField.<init>()
at java.lang.Class.getConstructor0(Unknown Source)
... 77 more

在我的 .fxml 文件中,我也包含了 <?import gui.PersistentPromptTextField?>,但显然我遗漏了一些东西。

由于 FXMLLoader 引发的错误是(默认情况下)尝试使用其无参数构造函数实例化给定的 class。如果你没有定义,试试吧。

使用带有一些参数的构造函数实例化,需要使用@NamedArgs注解。有关详细信息,请参阅 this comprehensive answer