string To Color - Java 2D Graphics

Java examples for 2D Graphics:Color String

Description

string To Color

Demo Code


//package com.java2s;
import java.awt.Color;
import java.lang.reflect.Field;

public class Main {
    public static void main(String[] argv) throws Exception {
        String value = "java2s.com";
        System.out.println(stringToColor(value));
    }//from   w  ww  .j  a  v  a  2  s.  c  o  m

    public static Color stringToColor(String value) {
        if (value == null) {
            return Color.black;
        }
        try {
            // get color by hex or octal value
            return Color.decode(value);
        } catch (NumberFormatException nfe) {
            // if we can't decode lets try to get it by name
            try {
                // try to get a color by name using reflection
                final Field f = Color.class.getField(value);

                return (Color) f.get(null);
            } catch (Exception ce) {
                // if we can't get any color return black
                return Color.black;
            }
        }
    }
}

Related Tutorials