Search code examples
javastaticinitializationjava-2djapplet

JAppet loading images


I made a game using JFrame, and now I want to deploy it in JApplet, yet I get the following exception:

java.lang.ExceptionInInitializerError

As much as Google told me it is caused by static initializers, and the only thing I do in my static initialization blocks is call to the following function:

public static BufferedImage[] loadAnimation (String fileName, int subimagewidth, int subimageheight, int pixelsbetweensprites) {


    BufferedImage spr = null;
    BufferedImage[] animation;

    int x, y;           //amount of images in each direction

    try {
        Object ob = new Object();
        spr = ImageIO.read(ob.getClass().getResourceAsStream(fileName));
    } catch (IOException ex) {
        System.exit(0);
        Logger.getLogger(AnimationLoader.class.getName()).log(Level.SEVERE, null, ex);
    }

    x = spr.getWidth() / subimagewidth;
    y = spr.getHeight() / subimageheight;

    animation = new BufferedImage[x*y];

    for (int i = 0; i < x; i++) {
        for (int j = 0; j < y; j++) {
            animation[j*x+i] = spr.getSubimage(i*(subimagewidth + pixelsbetweensprites), j*(subimageheight+pixelsbetweensprites), subimagewidth, subimageheight);
        }
    }

    return animation;

}

Is this problem occurs because it is JApplet, or because it is unsigned? How to fix it (preferably without spending money on signature)?


Solution

  • This:

    Object ob = new Object();
    spr = ImageIO.read(ob.getClass().getResourceAsStream(fileName));
    

    You probably want to load the image from the same location your code originates from (e.g. a jar file). Instead you ask java.lang.Object.class to give back the stream of the image which is probably not you want (this would search the filename resource in the internal libraries of the JRE or JDK - more specifically in the rt.jar file).

    If indeed you want to load the image from the same jar your class files originates from, you should acquire the stream like this:

    InputStream in = YourClass.class.getResourceAsStream(filename);
    

    You should pass this InputStream to your loadAnimation() method, or pass both the Class along with the file name to be used to get the stream of the image.