猿问

Jar 找不到 .fxml 文件的路径

我正在用 javafx 开发桌面应用程序,与 Intellij 不同,他的 jar 文件返回 null for getClass().getResource(pagePath).


当我使用 Intellij 构建和运行应用程序时,一切正常并完成工作,但在我创建工件并使用命令行运行 .jar 文件后,出现错误:


'线程“JavaFX 应用程序线程”中的异常


java.lang.NulPointerException:需要位置。' 经过多次研究和测试后,我发现调用getClass().getResource(pagepath)在 .jar 中返回 null,但在 Intellij 中没有。我试图改变写路径的方式,改变模式和改变项目的结构。


这是有罪的方法


protected void loadPage(ActionEvent event, String pagePath) throws IOException {

        System.out.println(getClass().getResource(pagePath));

        Parent pageParent = FXMLLoader.load(getClass().getResource(pagePath));

        Scene newPage = new Scene(pageParent);

        pageParent.getStylesheets().add(Views.CSS);

        Stage window = (Stage) ((javafx.scene.Node)event.getSource()).getScene().getWindow();

        window.setScene(newPage);

        window.show();

    }

程序的初始化工作,.jar 文件在主类中使用此方法正确启动第一页。


@Override

    public void start(Stage primaryStage) throws Exception{

        Parent root = FXMLLoader.load(getClass().getResource(Views.XML_ACCUEIL));

        primaryStage.getIcons().add(new Image(Views.APP_ICON));

        primaryStage.setTitle(Views.APP_NAME);

        primaryStage.setScene(new Scene(root, Views.WIDTH, Views.HEIGHT));

        primaryStage.show();

    }

视图类如下所示:


public class Views {

    public static final String home = System.getProperty("user.home");

    public static final String REGISTER_FOLDER = home + File.separator + "Desktop" + File.separator;

    public static final String XML_ACCUEIL = "resources/accueil.fxml";

    public static final String XML_VENTE_FORM = "resources/vente_form.fxml";

    public static final String XML_DEPOT_FORM = "resources/depot_form.fxml";

    public static final String XML_TECHNIQUE_FORM_1 = "resources/technique_form_1.fxml";

    public static final String XML_TECHNIQUE_FORM_2 = "resources/technique_form_2.fxml";

    public static final String XML_TECHNIQUE_FORM_3 = "resources/technique_form_3.fxml";

}


森栏
浏览 167回答 1
1回答

慕尼黑5688855

我会期望"/accueil.fxml"或"/resources/accueil.fxml"。使用 7tzip 等查看 jar 中的真实路径。资源路径"resources/accueil.fxml"表示在类路径中,getClass()(类的包目录)的子目录下应该有一个子目录resources。另一个错误是当不启动 jar 时,文件名在 Windows 中只区分大小写。jar (zip) 文件,Linux 和 Mac 都有区分大小写的文件名。检查区分大小写的拼写。
随时随地看视频慕课网APP

相关分类

Java
我要回答