Hey, I've never really used packages before so I was wondering if what I am doing is possible.

i have a package called spacewars with all my classes. I then created another package from that called spacewars.resources.

I am not sure what the best way to access those resources is.

ImageIcon ship = new ImageIcon((shipImage));
        image = ship.getImage();

Where shipImage is the url/directory. I do not know how to format/write the directory to access another package. I would also like to know if this is a good way to go about things, or if I should just keep the resources outside a package etc.

6 Years
Discussion Span
Last Post by ~s.o.s~

Use the getResource() method of the ClassLoader class for loading resources in a location-independent manner relative to your classloader path. This path is normally the classpath which you set (-cp) when spawning the Java process.

This method is capable of loading any classpath resource, not just packaged resources. Hence you can either have a images directory which hosts the images or a "game.images" package. For e.g. lets assume that your JAR contains the entire folder structure for the class files based on the package name along with a images and sounds directory, something like:

  - pkg
    - spacewars
      - images
  - images (normal directory)

The methodology for loading the resources would stay the same:

final ClassLoader loader = getClass().getClassLoader();
final URL url = loader.getResource("images/one.png");
// OR
final URL url = loader.getResource("pkg/spacewars/images/one.png");

One suggestion: AFAIK, almost all games have the concept of "resource managers" which are contract (interface) driven classes which are solely responsible for loading game assets. For the time being you can have a singleton ResourceLoader class which loads the resources for you. This way you can abstract the resource loading and change the strategy your resources are loaded without a lot of pain. E.g. in the future you might want to pack your resources in a custom archive format and then read the resource from it. If you litter your code would all the getResource() calls, it might be a bit difficult and cumbersome to move to a custom archive format. But if you have encapsulated the loading, the change would be required only in a single place.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.