parse Color String - Java 2D Graphics

Java examples for 2D Graphics:Color String

Description

parse Color String

Demo Code


import java.awt.Color;
import java.util.ArrayList;
import java.util.List;

public class Main{
    public static void main(String[] argv) throws Exception{
        String input = "java2s.com";
        System.out.println(parseColor(input));
    }/* w  w  w.j  a  v  a 2 s .  c  om*/
    public static Color parseColor(final String input) {
        Color color = null;

        if (input.matches("^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6})$")) {
            // We have a hex value with either 6 (rgb) or 8 (rgba) digits
            int r = Integer.parseInt(input.substring(1, 3), 16);
            int g = Integer.parseInt(input.substring(3, 5), 16);
            int b = Integer.parseInt(input.substring(5, 7), 16);

            if (input.length() > 7) {
                int a = Integer.parseInt(input.substring(7, 9), 16);
                color = new Color(r, g, b, a);
            } else {
                color = new Color(r, g, b);
            }
        } else {
            // Check for color string
            color = ColorKeyword.getColor(input);
        }

        return color;
    }
}

Related Tutorials