问题描述
我在 Eclipse 中有一个 gradle 项目.这是我的项目结构
I have a gradle project in eclipse. Here is the structure of my project
我在 scr/main/resources/css
中有 css 资源 styleclass.css
.首先我尝试使用
I have css resource styleclass.css
in scr/main/resources/css
. First I tried to access it using
scene.getStylesheets().add("css/styleclass.css");
但我收到警告 resource not found.
我也尝试删除 module-info.java
文件.但结果是一样的.
But I was getting warning resource not found.
I also tried it by removing module-info.java
file. But result is same.
然后我尝试使用
String urlString = ComboBoxStyling.class.getClassLoader().getResource("css/styleclass.css").toExternalForm();
问题是,如果我删除 moduele-info.java
并应用样式表,此行会起作用.但是使用 module-info.java
我得到空指针异常.
Problem is, this line works if I remove moduele-info.java
and style sheet applied. But with module-info.java
I am getting null pointer exception.
我知道的不多,但至少我知道类加载器在 Java 9 中有变化.那么我如何在 Java 9 中做同样的事情.我的 module-info.java
文件包含以下内容
I don't know much but atleast I know that class loader have changes in Java 9. So how can I do the same in Java 9. My module-info.java
file contains the following
module pk.training.basit {
exports pk.training.basit;
requires transitive javafx.controls;
}
谢谢&问候
巴斯特·马哈茂德·艾哈迈德
Basit Mahmood Ahmed
推荐答案
来自 ClassLoader.getResource
JavaDoc:
From ClassLoader.getResource
JavaDoc:
命名模块中的资源遵循 Module.getResourceAsStream 指定的封装规则.此外,除了资源名称以.class"结尾的特殊情况外,此方法只会在无条件打开包时(即使此方法的调用者在同一个包中)才会在命名模块的包中查找资源模块作为资源).
因此,要解决您的问题,您应该打开包 css
:
So, to fix your issue, you should make the package css
open:
module pk.training.basit {
exports pk.training.basit;
requires transitive javafx.controls;
opens css;
}
这篇关于如何在 Java 9 中使用类加载器访问资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!