我正在使用NetBeans开发一个Java FXML应用程序。出于结构化的目的,我希望所有可重用的代码都在一个外部的自制库中(只是另一个NetBeans Java项目)。
我希望库代码动态加载给定的fxml视图,使用如下:
class Loader {
public static void load(Stage stage, String view) {
Parent root = FXMLLoader.load(Loader.class.getClass().getResource(view);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
}
基本fxml应用程序中的主类:
class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception, NullPointerException {
Loader.load(stage, "FXMLDocument.fxml");
}
}
但是fxml视图文件位于基础的fxml应用程序项目中(而不是放置代码的外部库项目)。我对这种高级Java的东西不是很有经验,但我猜这是一个classpath
问题。
getResource()行触发的错误:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:367)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:305)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:894)
at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:56)
at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:158)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NullPointerException: Location is required.
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3223)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3191)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3164)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3140)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3120)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3113)
.....
只需将包名添加到文件路径中即可Loader.load(stage, "package/FXMLDocument.fxml");
…