Where put “resources” dir on eclipse

2019-07-18 21:49发布

问题:

My project is a eclipse Java project and it structure is

\Game\src

\Game\resources

But this code returns a exception:

image = new ImageIcon(new URL("resources\\Monster.png"));

java.net.MalformedURLException: no protocol: resources\Monster.png

What's wrong?

回答1:

In eclipse, make the resources folder a Source folder so that it adds the files inside it to the classpath when it launches your application.

Then use

image = new ImageIcon(YourClass.class.getResource("/monster.png"));

where YourClass is your class.

The Class#getResource(String) call

Finds a resource with a given name.

It does this by looking for it in your application's classpath based on some naming rules described in the javadoc.