Skip to content
Advertisement

Java: how to add image references properly from a non-src folder

it’s again about VSCode and Java (I start learning it). I have a little test program that loads images and works fine when started in the VSCode IDE. I have also seen here that I must somehow load the pics from a “classpath” – so I added a classpath for the “pics” folder shown in the screenshot.

I see that the pics are loaded into the jar, but they are not found at runtime (maybe because of the sub-folder or because they are not in src – but I want to have them in a separate folder of course). See the source code also in the screenshot – how should I do better to have the jar working, but also can test the code in the IDE? At the moment i do like this:

PicLabel pl1 = new PicLabel(new File(
                "./pics/Screenshot from 2022-07-20 15-40-16.png"));

my folder setup

Advertisement

Answer

new File is literal. It means file. Physically, on disk. Also, . means ‘current working dir’, which is whatever the dir is where the user starts your java process, i.e. who knows – you cannot rely on it being anything specific, thus, this code is doomed. It can’t ever work. (Or rather, it only works if the user is following instructions to the letter and users don’t work like that).

Given that java apps are distributed as jars, you want images to be entries in those jars. They aren’t files, thus new File means you’ve lost.

The right move is to use MyClass.class.getResource("/pics/Screenshot.png").

This gets you a URL which you can pass to e.g. ImageIcon and the like. I have no idea what PicLabel is, but it’ll probably take a URL. If it does not, there’s:

try (InputStream in = MyClass.class.getResource("/pics/Screenshot.png") {
  // use 'in' here
}
  • if it doesn’t take a URL, it takes an InputStream. And if that’s not possible either, it’s a silly API; stop using it, find a non-broken library instead.

This will look in the same place as where YourClass.class lives. Even if it is in a jar. Even if the current working dir isn’t what you thought it was. Stick /pics/Screenshot.png inside the jar and the above line will ‘find’ it.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement