How to access resource using class loader in Java 9

前端 未结 2 815
灰色年华
灰色年华 2020-12-06 14:52

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

I have css resource styleclass.css in scr/main/resources/css

相关标签:
2条回答
  • 2020-12-06 15:31

    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.

    0 讨论(0)
  • 2020-12-06 15:41

    From ClassLoader.getResource JavaDoc:

    Resources in named modules are subject to the encapsulation rules specified by Module.getResourceAsStream. Additionally, and except for the special case where the resource has a name ending with ".class", this method will only find resources in packages of named modules when the package is opened unconditionally (even if the caller of this method is in the same module as the resource).

    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;
    }
    
    0 讨论(0)
提交回复
热议问题