如何使用Java 9中的类加载器访问资源 [英] How to access resource using class loader in Java 9
问题描述
我在eclipse中有一个gradle项目。这是我项目的结构
I have a gradle project in eclipse. Here is the structure of my project
我有css资源 styleclass.css
在 scr / main / resources / 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");
但我收到警告资源未找到。
我还尝试删除 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
Basit Mahmood Ahmed
推荐答案
你应该把你的css放入与使用它的类相同的包,然后使用Class.getResource来访问它,使用相对的Path。
You should put your css in the same package as the class which uses it, then use Class.getResource to access it, with the relative Path.
src/main/java:
pk.training.basit
ComboBoxStyling.java
src/main/resources:
pk.training.basit
ComboBoxStyling.css
然后在源代码中:
scene.getStylesheets().add(
ComboBoxStyling.class.getResource("ComboBoxStyling.css").toExternalForm());
我个人认为将css和类放在同一目录中更好的做法,然后configure gradle so它可以获取src / main目录中的资源。它允许具有类似于其他GUI产品(Angular)的体系结构,其将包括源的屏幕的所有资源放置在同一目录中,例如FXML文件(例如,如果有的话)。
Personnally I think it's even a better practice to put the css and the class in the same directory, then configure gradle so It can take the resources in the src/main directory. It permits to have an architecture analog to other GUI products (Angular) which places all the resources of a screen including the source in the same directory, the FXML file for example if you had one.
这篇关于如何使用Java 9中的类加载器访问资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!