Java Hex to Color hexToColor(String s)

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

Description

Convert Hex String to Color.

License

GNU General Public License

Parameter

Parameter Description
s Must be of the form "#34a300" or "#3f2", otherwise throws Exception. Upper/lower case does not matter.

Return

The corresponding color.

Declaration

static public Color hexToColor(String s) 

Method Source Code


//package com.java2s;
// License: GPL. For details, see LICENSE file.

import java.awt.Color;

public class Main {
    /**/*  w  w  w  .j  a  v  a2 s  . co m*/
     * Convert Hex String to Color.
     * @param s Must be of the form "#34a300" or "#3f2", otherwise throws Exception.
     * Upper/lower case does not matter.
     * @return The corresponding color.
     */
    static public Color hexToColor(String s) {
        String clr = s.substring(1);
        if (clr.length() == 3) {
            clr = new String(new char[] { clr.charAt(0), clr.charAt(0), clr.charAt(1), clr.charAt(1), clr.charAt(2),
                    clr.charAt(2) });
        }
        if (clr.length() != 6)
            throw new IllegalArgumentException();
        return new Color(Integer.parseInt(clr, 16));
    }
}

Related

  1. hexToColor(String hex)
  2. hexToColor(String hexStr, boolean throwException, int[] buffer)
  3. hexToColor(String hexString)
  4. hexToColor(String hexString)
  5. hexToColor(String input)
  6. hexToColor(String string)
  7. hexToColor(String value)