FXML加载程序无法在带有模块的项目中找到.fxml文件 [英] FXML loader can't find .fxml file in the project with modules
问题描述
我有一个结构如下的项目:
I have a project with such structure:
我试图使用以下代码从Main类加载sample.fxml:
I trying to load sample.fxml from the Main class using this code:
Parent root = FXMLLoader.load(Main.class.getResource("../../submodule/src/java/sample.fxml"));
但是它不起作用. sample.fxml文件代码为:
but it doesn't work. The sample.fxml file code is:
<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<GridPane fx:controller="sample.Controller"
xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
</GridPane>
问题是FXML加载程序找不到此位置.该怎么解决?
The problem is that FXML loader can't find this location. How to solve it?
推荐答案
我建议遵循以下基本的maven包结构:
I would suggest to follow the basic maven package structure, like this:
src
|--main
|--java
|--resource (put your FXML file into this folder)
那么以下方法应该起作用:
Then the following should work:
Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("sample.fxml"));
您还可以将FXML文件放入子文件夹:
You can also put your FXML file into a subfolder:
... = FXMLLoader.load(getClass().getClassLoader().getResource("layouts/sample.fxml"));
这里是一个链接,显示了getClass().getResource()
与getClass.getClassLoader().getResource()
之间的区别
(区别在于相对路径和绝对路径.如果您始终要从Maven项目的/resources
目录开始,则应使用getClass().getClassLoader().getResource()
.
Here is a link showing the difference between getClass().getResource()
vs getClass.getClassLoader().getResource()
(The difference is in relative vs absolute paths. If you always want to start from the /resources
directory in a Maven project, you should use getClass().getClassLoader().getResource()
.
Class.getResource( )和ClassLoader.getResource()?
这篇关于FXML加载程序无法在带有模块的项目中找到.fxml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!