如何在外部自制库中加载资源?

时间:2014-07-01 16:30:28

标签: java netbeans resources classpath

我正在使用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视图文件位于bacis 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)
.....

1 个答案:

答案 0 :(得分:0)

只需将包名称添加到文件路径中即可 Loader.load(stage, "package/FXMLDocument.fxml"); ....