简体   繁体   English

JavaFX FXML文件加载仅需1秒

[英]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. 我正在JavaFX中构建应用程序,并且正在为布局加载FXML文件。 At the beginning, I had all of my .fxml files in my java classpath. 一开始,我所有的.fxml文件都位于我的java类路径中。

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 这就是我加载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). 它可能看起来不漂亮,但是可以工作(System.getProperty(“ jdir”)只是光盘上.jar的位置)。 Java finds the file, but ALWAYS takes EXACTLY one second to do so, on each file (FXML File sizes range from 1kb to 6kb) Java找到了文件,但在每个文件上总是要花一秒钟的时间(FXML文件大小从1kb到6kb)

So the problem I now have, is that my FXML takes way too long to load. 所以我现在遇到的问题是我的FXML加载时间太长。 Back when I had my FXML in the classpath, there was no delay. 回到我将FXML放在类路径中时,没有延迟。

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.) 我希望有人可以帮助我消除此延迟,或者帮助我解决如何从.jar加载FXML的问题(据我所知,您只能通过Streams从jar加载资源,但是FXMLLoader不接受流,因此我被卡住了。)

First of all, you can move the System.getProperty("jdir") outside, because like this you will call it each time you load a fxml. 首先,您可以将System.getProperty(“ jdir”)移到外面,因为这样每次加载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: 但是问题是,为什么不将fxml文件放在资源下,然后调用:

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. 延迟是由以下事实造成的:您的jar未由类加载器加载(因为它不在类路径上)并且资源不容易获得,因此在您可以使用jar文件内容之前会有一些延迟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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