JavaFX jar 未加载 JAR 文件,但在将代码编译为应用程序时加载正常

JavaFX jar is not loading with JAR file but loads fine when compiling code as application

在 IntelliJ 中编译为应用程序时,我可以很好地构建和启动程序。但是,当我打包和部署并尝试双击 jar 时,没有任何反应。我决定从那里使用 Git Bash 和 运行 它,我看到它抛出 NullPointerException。下面是 JavaFX main class、我的文件结构和抛出的错误。

为什么我在 jar 中得到 NullPointerException,但在 IntelliJ 中构建和编译时工作正常?

如果我遗漏了任何信息,请告诉我。谢谢!

public class Main extends Application {

    private Stage stage;

    @Override
    public void start(Stage stage){
        this.stage = stage;
        this.stage.setTitle("My JavaFX App");
        initRootlayout();
    }

    private void initRootlayout(){
        try{
            Parent root = FXMLLoader.load(getClass().getResource("/view/main.fxml"));
            Scene scene = new Scene(root);
            stage.setScene(scene);
            scene.getStylesheets().add("css/default.css");
            stage.setResizable(false);
            stage.show();
        }

        catch(Exception e){
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

检查你的 jar 内容,主要是它缺少你的资源文件夹。 如果您使用 IntelliJ Artifacts 制作 jar,请确保将资源文件夹包含在 jar 中,File -> Project Structure -> Artifacts -> Select your artifact -> output layout tab -> -> Directory内容 -> Select 您的资源文件夹。 然后重建你的 jar