站内搜索: 请输入搜索关键词
当前页面: 在线文档首页 > JDK 5 Documentation v1.5.0, Java 2 SDK 英文文档

java.lang.IllegalArgumentException thrown in java.awt.Color constructor ... - JDK 5 Documentation v1.5.0, Java 2 SDK 英文文档

java.lang.IllegalArgumentException thrown in java.awt.Color constructor


Symptoms

When running an applet in a browser using the Sun JRE, an IllegalArgumentException is thrown in the java.awt.Color constructor. The same applet runs under the Microsoft 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 over-bound/under-bound values in the Color constructor was not well defined, and the Microsoft VM would automatically readjust the values to maximum color values and minimum color values automatically. The Sun JRE took a different approach, using an IllegalArgumentException to let the programmer know that they specified an out-of-bounds value.

Resolution

Code defensively to ensure only valid color values are passed to the Color constructor. For example,

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

The code should be changed to

        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

        N/A