我通过扩展现有控件创建了一个新控件,并且我想在我的 JavaFX 场景中使用这个新控件。我希望能够使用场景生成器编辑场景,但是将新控件添加到 FXML 文件后,我遇到了ClassNotFoundException
打开场景生成器时。
例如,这是我制作的一个类,它扩展了TextField
:
RegexLimitingTextField.java
public class RegexLimitingTextField extends TextField {
private String regexLimiter = ".*";
public void setRegexLimiter(String regex) {
this.regexLimiter = regex;
}
@Override
public void replaceText(int start, int end, String text) {
if (text.matches(regexLimiter))
super.replaceText(start, end, text);
}
@Override
public void replaceSelection(String replacement) {
if (replacement.matches(regexLimiter))
super.replaceSelection(replacement);
}
}
将此控件添加到我的 FXML 文件后...
sample.fxml
<?import javafx.scene.layout.GridPane?>
<?import sample.RegexLimitingTextField?>
<GridPane fx:controller="sample.Controller"
xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
<RegexLimitingTextField fx:id="textField" text="Test" />
</GridPane>
...加载 Scene Builder 2.0 时出现此错误:
Caused by: java.lang.ClassNotFoundException: sample.RegexLimitingTextField
at java.lang.ClassLoader.findClass(ClassLoader.java:530)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at javafx.fxml.FXMLLoader.loadTypeForPackage(FXMLLoader.java:2920)
at javafx.fxml.FXMLLoader.loadType(FXMLLoader.java:2909)
at javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2850)
... 23 more
为什么场景生成器找不到我的新控件?我需要做什么才能让它找到并能够使用我的新控件?
如果需要的话,以下是其他文件:
Main.java
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setScene(new Scene(root, 200, 200));
primaryStage.show();
}
}
Controller.java
public class Controller implements Initializable {
public RegexLimitingTextField textField;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
textField.setRegexLimiter("\\w*");
}
}