Parses a hex color string (e.g. #FF0000 or FF0000) - Java 2D Graphics

Java examples for 2D Graphics:Color

Description

Parses a hex color string (e.g. #FF0000 or FF0000)

Demo Code

/**//w w  w  .  j  a  v  a2s .co  m
 * Copyright 1998-2008, CHISEL Group, University of Victoria, Victoria, BC, Canada.
 * All rights reserved.
 */
//package com.java2s;
import java.awt.Color;

public class Main {
    /**
     * Parses a hex color string (e.g. #FF0000 or FF0000).
     * If the color value couldn't be parsed correctly, null will be returned.
     * @param value   the hex color value to parse
     * @return the color represented by the string, or null if the string was malformed
     */
    public static Color hexStringToColor(String value) {
        Color c = null;
        if (value != null) {
            value = value.trim();
            if (value.startsWith("#")) {
                value = value.substring(1);
            }
            try {
                c = new Color(Integer.parseInt(value, 16));
            } catch (NumberFormatException ignore) {
                c = null;
            }
        }
        return c;
    }
}

Related Tutorials