类加载资源java,如何使用Java 9中的类加载器访问资源

I have a gradle project in eclipse. Here is the structure of my project

92Uxn.png

I have css resource styleclass.css in scr/main/resources/css. First I tried to access it using

scene.getStylesheets().add("css/styleclass.css");

But I was getting warning resource not found. I also tried it by removing module-info.java file. But result is same.

Then I tried it using

String urlString = ComboBoxStyling.class.getClassLoader().getResource("css/styleclass.css").toExternalForm();

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.

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;

}

Thanks & Regards

Basit Mahmood Ahmed

解决方案

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

Then in the source:

scene.getStylesheets().add(

ComboBoxStyling.class.getResource("ComboBoxStyling.css").toExternalForm());

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值