Scene.getStylesheets (). Add () does not work inside jar file

While I run my project directly from Eclipse, I have no problem with this:

scene.getStylesheets().add(getClass().getResource("/stylesheet.css").toExternalForm()); 

But as soon as I ran this code inside the jar file, the resource was not found ( NullPointerException ).

I tried moving the css file to my src folder and then only stylesheet.css as the path instead of /stylesheet.css , but this leads to the same problem: it works fine using Eclipse, but not from jar.

Tip . I am using the Zonskis Maven JavaFX Plugin to create a banner.

+4
source share
2 answers

I just took the time (yours) to create stupid maven profiles.

instead:

 scene.getStylesheets().add(getClass().getResource("/stylesheet.css").toExternalForm()); 

just write:

 scene.getStylesheets().add("stylesheet.css"); 

Here's how Zonski upload css files.

Of course, your stylesheet.css file should be in /src/main/resources or somewhere on CLASSPATH .

+5
source

Move the file to src/main/resources and add the css file:

 scene.getStylesheets().add(getClass().getClassLoader().getResource("stylesheet.css").toExternalForm()); 

Well, if you want to run it from jar, change stylesheet.css to stylesheet.bss ( binary css ), pack the application:

 mvn clean compile jfx:build-jar 

and run the jar.

 java -jar app.jar 

I have an ugly hack to make it available for use (I use Netbeans , awesome maven ):

I create a project.properties file in the src/main/resources directory,

 file_css= ${file_css} // by default I use *.css file. 

And make it filtered in my POM file:

 ... <build> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <groupId>com.zenjava</groupId> <artifactId>javafx-maven-plugin</artifactId> <version> 1.5 </version> <configuration> .... </configuration> </plugin> </plugins> </build> ... 

And create two maven profiles, one for dev and one for production (packaging in a jar):

 <profiles> <profile> <id>production</id> <properties> <file_css>stylesheet.bss</file_css> </properties> </profile> <profile> <id>dev</id> <properties> <file_css>stylesheet.css</file_css> </properties> </profile> </profiles> 

So , you upload the css file as follows:

 scene.getStylesheets().add(getClass().getClassLoader().getResource(ResourceBundle.getBundle("project").getString("file_css")).toExternalForm()); 

I use the production profile for packaging and dev for normal activities like compile, test, run .


Edit: The full example is posted on github .

+1
source

All Articles