TestTerrain.class.getClassLoader()?

I think I understand what a class loader is, but I don't understand why I have to use it to load a texture as in the following code from the terrain tutorial:


pt.addTexture(new ImageIcon(TestTerrain.class.getClassLoader()
                        .getResource("jmetest/data/texture/grassb.png")), -128, 0, 128);



I realise this is a basic question.  ://

It's just a way to create an URL to a resource. You can do this in another way if you like, just look at the constructor of ImageIcon (a javax.swing class), or you can of course create the URL differently.

So I wouldn't do something like (pseudo code):



TextureManager.Load("/opt/media/image.jpg");



Sorry - coming from a C++/Pascal background here.





Thanks again

You could do something like this, yes:

pt.addTexture(new ImageIcon(new URL("file:///home/user/jmetest/data/texture/grassb.png"), -128, 0, 128);



Though using the classloader to obtain a URL is done more often, because you don't need to struggle with finding the file: the classloader searches in the directories it uses for finding its classes. This e.g. means that it does not matter if you have copied your image into your classpath directory, or it is in a library or somewhere in the net where you have your WebStart resources...

P.S. Have a look at the JavaDoc of getResource()

Ah now I get it! Thanks for the info.

Do I have to use TestTerrain (the main class) or can I use any class within the app? I'm writing a separate class (LevelLoader) to generate the terrain, so I don't have access to the TestTerrain main class. So I thought I could use:



LevelLoader.class.getClassLoader() etc…



But that gives:



java.lang.NullPointerException

        at javax.swing.ImageIcon.<init>(ImageIcon.java:138)

        at LevelLoader.buildTerrain(LevelLoader.java:79)

        at Main.simpleInitGame(Main.java:58)

        at com.jme.app.SimpleGame.initGame(Unknown Source)

You can use it with any class. But be aware that the classloader of the class most probably (depending on the kind of classloader) searches in the same path where the class is found. So the file must be e.g. in the same jar.



You get a NPE if the returned URL is null, as the file was not found - check that before using the url-var.