Ownaginatious
Ownaginatious

Reputation: 797

How do I correctly add my folder to the classpath in Eclipse?

So I'm trying to simply add a folder of resources I must load in my application using getClass().getResource(...).

I've tried just about everything, but I can't seem to get it to work.

According to the layout below, what I want to do is to load a resource from the scenes-fxml folder from the ViewManager class, which logically I should be able to do with:

getClass().getResource("/scenes-fxml/MainScreen.fxml");

However, it does not work. I've tried adding the folder to the Eclipse class path in the run time (... which feels odd seeing as it should be captured within the context of the project folder, which is already there by default in eclipse).

I also tried changing the folder into a source folder, which didn't help. Is there something else I can do?

Here is my project layout: https://i.sstatic.net/zmUY3.png

Upvotes: 0

Views: 146

Answers (2)

Rob
Rob

Reputation: 5481

All folders in your project that are not on the classpath (not source-folders in eclipse) can't be found by getResource().

EDIT:

So you have to copy "scenes-fxml" into the src-folder to use "/scenes-fxml/MainScreen.fxml". The leading slash in your path tells the resource loader to search from root of all classpath folders (here the src folder). As an alternative you can mark the "scenes-fxml" as source folder so that it's added to the classpath and use "/MainScreen.fxml" to find it.

You may also use a relative path to search for resources. Then you need a path relative to the class that calls getResource()...

Here's the java doc (IMO a bit complicated) http://download.java.net/jdk8/docs/technotes/guides/lang/resources.html

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691625

It's quite simple actually. Let's say that scenes-fxml is marked as a source folder. Everything directly under this folder is thus in the root, default package. Just like if you had a .java file directly under src, the class defined in this .java file would be in the default package.

So, mark the scenes-fxml as a source folder, and use

getClass().getResource("/MainScreen.fxml");

If you want to use the path /scenes-fxml/MainScreen.fxml, then the MainScreen.fxml must be in the "package" scenes-fxml, and you thus need a folder named scenes-fxml under (and not as) one of your source folders. You shouldn't use a - character though, since it would make your package name invalid.

Upvotes: 0

Related Questions