我正在用 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";}
1 回答

慕尼黑5688855
TA貢獻1848條經驗 獲得超2個贊
我會期望"/accueil.fxml"
或"/resources/accueil.fxml"
。使用 7tzip 等查看 jar 中的真實路徑。
資源路徑"resources/accueil.fxml"
表示在類路徑中,getClass()
(類的包目錄)的子目錄下應該有一個子目錄resources
。
另一個錯誤是當不啟動 jar 時,文件名在 Windows 中只區分大小寫。jar (zip) 文件,Linux 和 Mac 都有區分大小寫的文件名。檢查區分大小寫的拼寫。
添加回答
舉報
0/150
提交
取消