Java Hex to Color hexToColor(String color)

Here you can find the source of hexToColor(String color)

Description

Convert html hex string to Color.

License

Open Source License

Parameter

Parameter Description
color the String (in RGB hexadecimal format) to convert

Return

the java.awt.Color

Declaration

public final static Color hexToColor(String color) 

Method Source Code


//package com.java2s;
/*//from  w w w .ja  v a  2s. c  o  m
 * @(#)TextUtility.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */

import java.awt.Color;

public class Main {
    /**
     * Convert html hex string to Color. If the hexadecimal string is not
     * a valid character, <code>Color.black</code> is returned.
     * Only the first six hexadecimal characters are considered; any
     * extraneous values are discarded. Also, a leading "#", if any, is allowed
     * (and ignored).
     * @param color the String (in RGB hexadecimal format) to convert
     * @return the java.awt.Color
     */
    public final static Color hexToColor(String color) {
        try {
            if (color.charAt(0) == '#') {
                color = color.substring(1, 7);
            }

            int[] col = new int[3];

            for (int i = 0; i < 3; i++) {
                col[i] = Integer.parseInt(color.substring(i * 2, (i * 2) + 2), 16);
            }

            return new Color(col[0], col[1], col[2]);
        } catch (Exception e) {
            return Color.black;
        }
    }
}

Related

  1. hexToColor(final String hex)
  2. hexToColor(String color)
  3. hexToColor(String colorHex)
  4. hexToColor(String hex)
  5. hexToColor(String hexStr, boolean throwException, int[] buffer)