简体   繁体   中英

JavaFX FXML File takes exactly 1 second to load

I'm building an application in JavaFX, and I'm loading FXML files for the layouts. At the beginning, I had all of my .fxml files in my java classpath.

Since I'm kinda making a game engine, I decided to move everything outside the classpath, so I now have a file system that looks like this:

Folder[javafx]
    editor.fxml
program.jar

This is how I'm loading my FXML

FXMLLoader.load(new URL("file:////" + System.getProperty("jdir") + "/javafx/" + name + ".fxml"));

It might not look pretty, but it works (System.getProperty("jdir") is just the location of the .jar on the disc). Java finds the file, but ALWAYS takes EXACTLY one second to do so, on each file (FXML File sizes range from 1kb to 6kb)

So the problem I now have, is that my FXML takes way too long to load. Back when I had my FXML in the classpath, there was no delay.

I hope, that someone could either help me with removing this delay, or on how I can load the FXML from the .jar (From my knowlege, you can only load resources from jars via Streams, but FXMLLoader doesn't take streams, so I'm stuck.)

First of all, you can move the System.getProperty("jdir") outside, because like this you will call it each time you load a fxml.

So instead of

FXMLLoader.load(new URL("file:////" + System.getProperty("jdir") + "/javafx/" + name + ".fxml"));

Do something like:

 String jdirProp = System.getProperty("jdir"); 

And then reuse this value on all the calls that follow.

FXMLLoader.load(new URL("file:////" + jdirProp + "/javafx/" + name + ".fxml"));

But the question is, why don't you put your fxml files under resources and just call:

FXMLLoader.load(getClass().getResource("yourfile.fxml"));

This is the fastest and most elegant way. The delay is caused by the fact that your jar is not loaded by a classloader (since it is not on the classpath) and the resource is not readily available, so there is a bit of a delay until you can use the jar files content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM