Java Color Create toColor(String pString)

Here you can find the source of toColor(String pString)

Description

Parses a string to a Color.

License

Open Source License

Parameter

Parameter Description
pString the string representation of the color

Exception

Parameter Description
IllegalArgumentException if the string does not map to a color.

Return

the Color object, or null if the argument is null

Declaration

public static Color toColor(String pString) 

Method Source Code


//package com.java2s;
import java.awt.*;

import java.lang.reflect.Field;

import java.lang.reflect.Modifier;

public class Main {
    /**//from  w ww .j  a  v a2s.  c  o  m
     * Parses a string to a Color.
     * The argument can be a color constant (static constant from
     * {@link java.awt.Color java.awt.Color}), like {@code black} or
     * {@code red}, or it can be HTML/CSS-style, on the format:
     * <UL>
     * <LI>{@code #RRGGBB}, where RR, GG and BB means two digit
     * hexadecimal for red, green and blue values respectively.</LI>
     * <LI>{@code #AARRGGBB}, as above, with AA as alpha component.</LI>
     * <LI>{@code #RGB}, where R, G and B means one digit
     * hexadecimal for red, green and blue values respectively.</LI>
     * <LI>{@code #ARGB}, as above, with A as alpha component.</LI>
     * </UL>
     *
     * @param pString the string representation of the color
     * @return the {@code Color} object, or {@code null} if the argument
     *         is {@code null}
     * @throws IllegalArgumentException if the string does not map to a color.
     * @see java.awt.Color
     */
    public static Color toColor(String pString) {
        // No string, no color
        if (pString == null) {
            return null;
        }

        // #RRGGBB format
        if (pString.charAt(0) == '#') {
            int r = 0;
            int g = 0;
            int b = 0;
            int a = -1;// alpha

            if (pString.length() >= 7) {
                int idx = 1;

                // AA
                if (pString.length() >= 9) {
                    a = Integer.parseInt(pString.substring(idx, idx + 2), 0x10);
                    idx += 2;
                }
                // RR GG BB
                r = Integer.parseInt(pString.substring(idx, idx + 2), 0x10);
                g = Integer.parseInt(pString.substring(idx + 2, idx + 4), 0x10);
                b = Integer.parseInt(pString.substring(idx + 4, idx + 6), 0x10);

            } else if (pString.length() >= 4) {
                int idx = 1;

                // A
                if (pString.length() >= 5) {
                    a = Integer.parseInt(pString.substring(idx, ++idx), 0x10) * 0x10;
                }
                // R G B
                r = Integer.parseInt(pString.substring(idx, ++idx), 0x10) * 0x10;
                g = Integer.parseInt(pString.substring(idx, ++idx), 0x10) * 0x10;
                b = Integer.parseInt(pString.substring(idx, ++idx), 0x10) * 0x10;
            }
            if (a != -1) {
                // With alpha
                return new Color(r, g, b, a);
            }

            // No alpha
            return new Color(r, g, b);
        }

        // Get color by name
        try {
            Class colorClass = Color.class;
            Field field = null;

            // Workaround for stupidity in Color class constant field names
            try {
                field = colorClass.getField(pString);
            } catch (Exception e) {
                // Don't care, this is just a workaround...
            }
            if (field == null) {
                // NOTE: The toLowerCase() on the next line will lose darkGray
                // and lightGray...
                field = colorClass.getField(pString.toLowerCase());
            }

            // Only try to get public final fields
            int mod = field.getModifiers();

            if (Modifier.isPublic(mod) && Modifier.isStatic(mod)) {
                return (Color) field.get(null);
            }
        } catch (NoSuchFieldException nsfe) {
            // No such color, throw illegal argument?
            throw new IllegalArgumentException("No such color: " + pString);
        } catch (SecurityException se) {
            // Can't access field, return null
        } catch (IllegalAccessException iae) {
            // Can't happen, as the field must be public static
        } catch (IllegalArgumentException iar) {
            // Can't happen, as the field must be static
        }

        // This should never be reached, but you never know... ;-)
        return null;
    }

    /**
     * Gets the first substring between the given string boundaries.
     * <p/>
     *
     * @param pSource              The source string.
     * @param pBeginBoundaryString The string that marks the beginning.
     * @param pEndBoundaryString   The string that marks the end.
     * @param pOffset              The index to start searching in the source
     *                             string. If it is less than 0, the index will be set to 0.
     * @return the substring demarcated by the given string boundaries or null
     *         if not both string boundaries are found.
     */
    public static String substring(final String pSource, final String pBeginBoundaryString,
            final String pEndBoundaryString, final int pOffset) {
        // Check offset
        int offset = (pOffset < 0) ? 0 : pOffset;

        // Find the start index
        int startIndex = pSource.indexOf(pBeginBoundaryString, offset) + pBeginBoundaryString.length();

        if (startIndex < 0) {
            return null;
        }

        // Find the end index
        int endIndex = pSource.indexOf(pEndBoundaryString, startIndex);

        if (endIndex < 0) {
            return null;
        }
        return pSource.substring(startIndex, endIndex);
    }

    /**
     * Converts a string to lowercase.
     *
     * @param pString the string to convert
     * @return the string converted to lowercase, or null if the argument was
     *         null.
     */
    public static String toLowerCase(String pString) {
        if (pString != null) {
            return pString.toLowerCase();
        }
        return null;
    }
}

Related

  1. toColor(int x)
  2. toColor(Node n)
  3. toColor(short rgb565)
  4. toColor(String background)
  5. toColor(String hexString)
  6. toColor(String str)
  7. toColors(boolean hasAlpha, int... colors)