You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaFX+Maven+H2项目启动报错:Application start方法异常

解决JavaFX Maven项目中FXML加载的Location is not set异常

你的核心问题是FXML文件路径写法错误,导致FXMLLoader无法定位到文件,抛出IllegalStateException: Location is not set.异常。以下是具体修正步骤:

1. 修正getResource路径

Maven项目中,src/main/resources下的文件会被编译到classpath根目录,因此不能使用项目相对路径src/main/resources/view/MainView,需要改用classpath下的相对路径,同时必须加上.fxml后缀:

修正后的App类代码:

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

public class App extends Application {
    @Override
    public void start(Stage stage) throws IOException {
        // 修正路径:使用classpath根目录下的相对路径,加上.fxml后缀
        FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource("/view/MainView.fxml"));
        Scene scene = new Scene(fxmlLoader.load(), 1280, 720);
        stage.setTitle("Finance Manager");
        stage.setScene(scene);
        stage.show();
    }

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

2. 验证文件结构

确保你的项目文件结构符合Maven规范:

  • FXML文件路径:src/main/resources/view/MainView.fxml(注意文件名大小写,Java对路径大小写敏感)
  • 编译后检查target/classes/view/目录下是否存在MainView.fxml,Maven会自动复制resources下的文件到该目录

3. 额外排查点(可选)

如果是模块化项目(存在module-info.java),需要在模块声明中添加对javafx.fxml的依赖,并开放包访问:

module pl.damianlebiedz.financemanager {
    requires javafx.controls;
    requires javafx.fxml;
    opens pl.damianlebiedz.financemanager to javafx.fxml;
    exports pl.damianlebiedz.financemanager;
}

内容的提问来源于stack exchange,提问作者Damian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 07:57:06