Alex Hope O'Connor
Alex Hope O'Connor

Reputation: 9694

Toolkit.getImage() from src folder

I am trying to get an image from the src/ folder in a package, however I am not having any success.

nekoPics[i] = tk.getImage(getClass().getResource(String.format("resources/pracs/neko/%s", nekosrc[i])));

Anyone sugestions?

Upvotes: 2

Views: 4248

Answers (2)

Joachim Sauer
Joachim Sauer

Reputation: 308051

When you use getClass().getResource() with a relative path (i.e. one not starting with /), then the path will be interpreted as relative to the package of the class you're using to load the resource.

So if you have that code in the class mypackage.MyClass, then requesting resources/pracs/neko/something will actually try to find mypackage/resources/pracs/neko/something relative to your classpath.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500805

Is it being copied into wherever your code is being built? Being in the src directory doesn't help if at execution time the class is in a bin directory (or a jar file).

Also note that if your class is in a package, then Class.getResource will work relative to that package by default. So if your package is foo.bar, it'll be looking for foo/bar/resources/pracs/neko/whatever. If you want to make it absolute, you could either use ClassLoader.getResource, or put a leading / at the start of your string:

String resource = String.format("/resources/pracs/neko/%s", nekosrc[i]);
nekoPics[i] = tk.getImage(getClass().getResource(resource));

or

String resource = String.format("resources/pracs/neko/%s", nekosrc[i]);
nekoPics[i] = tk.getImage(getClass().getClassLoader().getResource(resource));

Of course, if the reousrces directory is actually relative to your package, you shouldn't do that :)

Upvotes: 3

Related Questions