0

Let's say I'm creating a jar file and have an icon in an asset folder to be included in the jar.

So before using, stage.getIcons().add(icon); in my code is there any particular advantage or disadvantage to having the icon as

Image icon = new Image("Assets/Icon.png");

Vs.

Image icon = new Image(getClass().getResourceAsStream("Assets/Icon.png"));

Both seem to work fine, so I'm looking to pinpoint which I should generally gravitate towards and why.

There's a related topic here but it compares loading styles mostly with web applications.

Community
  • 1
  • 1
Legato
  • 609
  • 17
  • 24
  • Are you asking for the specific case of create a `javafx.scene.Image`, or for the more general case of using `getResourceAsStream` at all? – Dolda2000 Mar 17 '15 at 00:55
  • 1
    [`Image(String)`](http://docs.oracle.com/javafx/2/api/javafx/scene/image/Image.html#Image(java.lang.String)), the `String` value represents a `URL`. There may be additional internal processing that needs to go on to determine how best to process the request which might be better severed by passing an actual `URL` object – MadProgrammer Mar 17 '15 at 00:56
  • The alternate [Image(String url, boolean backgroundLoading)](http://docs.oracle.com/javase/8/javafx/api/javafx/scene/image/Image.html#Image-java.lang.String-boolean-) function has the ability to load the image asynchronously - so if you wish to load the image asynchronously, that the constructor to use rather than a stream based constructor. – jewelsea Mar 17 '15 at 04:21

1 Answers1

3

javafx.scene.Image(String) calls validateUrl, which does additional processing of the String value, including checking the current Threads contextClassLoader for the resource.

The advantage of using something like Class#getResourceAsString is you've already made the decisions for the class, which would be (slightly) faster, but also less ambiguous and would probably be easier to diagnose should you have issues (as you control the source mechanism for the image itself) and aren't leaving the decision making up to code that you don't immediately control (and since validateUrl is private static, can't change)

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366