IntelliJ IDEA中FXML相对路径报错‘Location is not set’的解决方案
解决JavaFX中FXML相对路径加载的「Location is not set」错误
问题描述
创建默认JavaFX程序后,仅重命名类并调整包结构,出现错误:
Caused by: java.lang.IllegalStateException: Location is not set.
使用FXML完整路径时程序正常运行,但希望通过相对路径加载,当前加载代码为:
FXMLLoader fxmlLoader = new FXMLLoader(Window.class.getResource("hello-view.fxml"));
项目结构:
src └── main ├── java │ └── com │ └── example │ └── demo │ ├── main │ │ └── Main.java │ └── rendering │ └── Window.java └── resources └── com └── example └── demo └── rendering └── hello-view.fxml
问题根源
你的Main.java中导入了错误的Window类:代码里引用的是JavaFX自带的javafx.stage.Window,而非你自己编写的com.example.demo.rendering.Window。调用错误类的getResource()方法时,会从JavaFX内置类的包路径查找资源,自然找不到你放在自定义包路径下的FXML文件。
解决步骤
1. 修正Main.java的导入语句
将Main.java中的:
import javafx.stage.Window;
替换为:
import com.example.demo.rendering.Window;
2. 确认资源路径匹配
你的hello-view.fxml已经放在resources/com/example/demo/rendering/下,和Window.java所在的java/com/example/demo/rendering/包结构完全对应,此时用Window.class.getResource("hello-view.fxml")就能通过相对路径正确找到资源。
修改后的Main.java代码
package com.example.demo.main; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.stage.Stage; import com.example.demo.rendering.Window; // 修正后的导入 import java.io.IOException; public class Main extends Application { @Override public void start(Stage stage) throws IOException { FXMLLoader fxmlLoader = new FXMLLoader(Window.class.getResource("hello-view.fxml")); Scene scene = new Scene(fxmlLoader.load(), 320, 240); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(); } }
额外验证
你的module-info.java已经正确配置了opens com.example.demo.rendering to javafx.fxml;,无需修改,这保证了FXML控制器能被JavaFX框架正确访问。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

