4
In Java it is nothing unusual to see codes that carry images, audio files, XML and other things like this:
final ImageIcon programLogo = new ImageIcon("res" + System.getProperty("file.separator") + "icon.png");
However, by the codes I’ve been reading and by what I’ve been seeing in the new Java libraries, a more experienced programmer would do this:
final ImageIcon programLogo = new ImageIcon(getClass().getResource("res/icon.png"));
The two forms do not reach the same result: The root path of the first example starts from the root path of Classloader and the root path of the second starts from the parent folder of . class, but the second seems to be more "professional", as it is what I see in applications and libraries "famous".
But I don’t understand why getResource is more used. What advantages does it offer? Because, in general, I should use getResource()?
getClass().getClassLoader().getResource("icon.png")
orgetClass().getResource("icon.png")
will basically search for the resource even when your application is already packaged...new ImageIcon("res" + System.getProperty("file.separator") + "icon.png")
will not find your "icon.png" file, unless it has been deleted from Packaging and added in the same folder as your.jar
.– Josh
@Josue, wouldn’t it be nice to turn that comment into a response? Why, until 19 hours after publication, is the only available and explanatory answer to the question.
– Gustavo Cinque