Convert a string into a Color object - Java 2D Graphics

Java examples for 2D Graphics:Color String

Description

Convert a string into a Color object

Demo Code


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

public class Main {
    public static void main(String[] argv) throws Exception {
        String inValue = "java2s.com";
        System.out.println(colourFromHex(inValue));
    }/*  w  w  w. ja  v  a2 s . co m*/

    /**
     * Convert a string into a Color object
     * @param inValue 6-character hex code
     * @return corresponding colour
     */
    public static Color colourFromHex(String inValue) {
        Color retVal = null;
        if (inValue != null && inValue.length() == 6) {
            try {
                final int redness = convertToInt(inValue.substring(0, 2));
                final int greenness = convertToInt(inValue.substring(2, 4));
                final int blueness = convertToInt(inValue.substring(4, 6));
                retVal = new Color(redness, greenness, blueness);
            } catch (NumberFormatException nfe) {
            } // colour stays null
        }
        return retVal;
    }

    /**
     * @param inPair two-digit String representing hex code
     * @return corresponding integer (0 to 255)
     */
    private static int convertToInt(String inPair) {
        int val = Integer.parseInt(inPair, 16);
        if (val < 0)
            val = 0;
        return val;
    }
}

Related Tutorials