get a color as a int from a string, alpha is set to 255 if we can not get the color then we return 0 - Java 2D Graphics

Java examples for 2D Graphics:Color String

Description

get a color as a int from a string, alpha is set to 255 if we can not get the color then we return 0

Demo Code


//package com.java2s;
import java.util.HashMap;
import java.util.Map;

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

    static Map stringToInt = new HashMap();

    /**
     * get a color as a int from a string, alpha is set to 255
     * if we can not get the color then we return 0
     */
    public static int getColor(String nm) {

        Integer color = (Integer) stringToInt.get(nm);
        if (color != null) {
            return color.intValue();
        }

        try {

            Integer result = Integer.decode(nm);

            // the 0xff000000 | means the alpha is 255
            return 0xff000000 | result.intValue();
        } catch (Exception ex) {

            //System.out.print("Error: unable to find color "+s+".\n"); // testing
            return 0;
        }
    }
}

Related Tutorials