java.lang.IllegalArgumentException Thrown in java.awt.Color Constructor


Symptoms

When running an applet in a browser using the Sun Java Runtime Environment (JRE) implementation, a java.lang.IllegalArgumentException is thrown in the java.awt.Color constructor. The same applet runs under the Microsoft Virtual Machine (VM).

Cause

This exception is caused by passing over-bound or under-bound values to the Color constructor 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 values beyond the upper and lower bounds in the Color constructor is not well defined. The Microsoft VM readjusts the values to maximum color values and minimum color values automatically. The Sun JRE uses a java.lang.IllegalArgumentException to indicate that an out-of-bounds value is specified.

Resolution

Code to ensure that only valid color values are passed to the Color constructor. For example, if you have the following structure of code:

  void Color newColor(int r, int g, int b)
        {
            return new Color(r, g, b);
        }

Change the code to ensure that only valid color values are passed to the color constructor as shown below:

        int ensureColorRange(int v)
        {
            if (v < 0)
                return 0;
            else if (v > 255)
                return 255;
            else
                return v;
        }
        void Color newColor(int r, int g, int b)
        {
            r = ensureColorRange(r);
            g = ensureColorRange(g);
            b = ensureColorRange(b);

            return new Color(r, g, b);
        }

Related Information

None.


Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.