NullPointerException thrown in java.awt.Graphics.drawImage()


Symptoms

When running an applet in a browser using the Sun JRE, a NullPointerException is thrown in the java.awt.Graphics.drawImage method. The same applet runs under the Microsoft VM.

Cause

This exception is caused by passing a null image to the drawImage method in the Sun JRE.

The Java class libraries in the Sun JRE have changed over time. Some APIs have been clarified, some have been deprecated, and some have had their implementation altered.

The result of passing a null image into the Graphics.drawImage method was not well defined, and the Microsoft VM treats null image as a no-op. However, most versions of the Sun JRE do not accept null as a valid image, thus resulting in a NullPointerException. As of 5.0, the specification has been clarified, and a null image argument is treated as a no-op.

Resolution

In JRE versions before 5.0, code defensively to ensure that only non-null images are passed to the drawImage method. For example:

        Graphics g = getGraphics();
    g.drawImage(img, 100, 100, this);

        The code should be changed to:

        Graphics g = getGraphics();
        if (img != null)
            g.drawImage(img, 100, 100, this);

Related Information

        N/A