IntelliJ中JavaFX控制器移至独立文件夹后加载FXML报错
JavaFX MVC架构下FXML加载NullPointerException(Location is required)解决方法
问题描述
在IntelliJ开发JavaFX项目,采用MVC架构拆分.java文件到不同文件夹后,从TournamentController类调用FXMLLoader加载match-view.fxml时抛出NullPointerException,错误提示为"Location is required"。此前控制器放在根包dux.tennis_tournament下时一切正常,移至controllers子包后出现问题,修改module-info.java、从Main类直接加载FXML等操作未解决,需符合MVC规范的正确配置。
项目关键代码与配置
Main.java
public class Main extends Application { @Override public void start(Stage stage) throws IOException { Parent parent = FXMLLoader.load(Main.class.getResource("main-view.fxml")); Scene scene = new Scene(parent, 900, 500); stage.setTitle("Tennis Tournament!"); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(); } }
TournamentController.java(报错相关代码)
public void startMatch(ActionEvent event) throws IOException { this.parent = FXMLLoader.load(getClass().getResource("match-view.fxml")); this.stage = (Stage) ((Node)event.getSource()).getScene().getWindow(); this.scene = new Scene(this.parent); this.stage.setScene(this.scene); this.stage.show(); }
module-info.java
module dux.tennis_tournament { requires javafx.controls; requires javafx.fxml; opens dux.tennis_tournament.controllers to javafx.fxml; exports dux.tennis_tournament.controllers; opens dux.tennis_tournament to javafx.fxml; exports dux.tennis_tournament; }
match-view.fxml控制器配置
fx:controller="dux.tennis_tournament.controllers.MatchController">
解决方案
1. 修正FXML资源路径
控制器移至controllers子包后,getClass().getResource("match-view.fxml")会从当前类所在的dux/tennis_tournament/controllers/路径查找文件。需根据FXML实际位置调整路径:
- 若FXML文件在根包对应的资源目录(如
src/main/resources/dux/tennis_tournament/),使用绝对路径(以/开头):this.parent = FXMLLoader.load(getClass().getResource("/dux/tennis_tournament/match-view.fxml")); - 若希望保持相对路径,将
match-view.fxml移至src/main/resources/dux/tennis_tournament/controllers/目录下,与控制器包结构对应。
2. 确认资源文件编译路径
在IntelliJ中确保资源文件被正确编译:
- 打开
File > Project Structure > Modules,检查Resources标签页是否正确标记了资源目录(默认是src/main/resources)。 - 编译后查看
target/classes目录,确认match-view.fxml的实际路径与代码中引用的路径一致。
3. 验证module-info.java配置
当前配置已正确开放控制器包给JavaFX FXML访问,无需修改:
module dux.tennis_tournament { requires javafx.controls; requires javafx.fxml; opens dux.tennis_tournament.controllers to javafx.fxml; exports dux.tennis_tournament.controllers; opens dux.tennis_tournament to javafx.fxml; exports dux.tennis_tournament; }
4. 确认FXML控制器全类名
match-view.fxml中的控制器全类名配置正确,无需调整:
fx:controller="dux.tennis_tournament.controllers.MatchController"
内容的提问来源于stack exchange,提问作者Gino
相关产品推荐
相关产品推荐

