Spec-Zone .ru
спецификации, руководства, описания, API

java.lang.NullPointerException Thrown in java.awt.Graphics.drawImage()


Symptoms

When running an applet in a browser using the Sun JavaTM Runtime Environment (JRETM), a java.lang.NullPointerException is thrown in the java.awt.Graphics.drawImage() method. The same applet runs without any error under the Microsoft Virtual Machine (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 their implementation altered.

The result of passing a null image into the Graphics.drawImage() method was not well defined. 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 java.lang.NullPointerException. As of JRE version 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, the following code shows:

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

        Change the above code to:

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

Related Information

        None.