Java Hex to Color hexToColor(String value)

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

Description

Convert a "#FFFFFF" hex string to a Color.

License

Open Source License

Parameter

Parameter Description
value the hex formatted color string (may begin with '#')

Return

the resulting Color instance

Declaration

public static final Color hexToColor(String value) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.awt.Color;

public class Main {
    /**/*w  w  w  .jav  a2 s .  c o  m*/
     * Convert a "#FFFFFF" hex string to a Color. If the color specification 
     * is bad, an attempt will be made to fix it up.
     *
     * @param value the hex formatted color string (may begin with '#')
     * @return the resulting Color instance
     */
    public static final Color hexToColor(String value) {

        String digits;
        if (value.startsWith("#")) {
            digits = value.substring(1, Math.min(value.length(), 7));
        } else {
            digits = value;
        }

        String hstr = "0x" + digits;
        Color c;
        try {
            c = Color.decode(hstr);
        } catch (NumberFormatException nfe) {
            c = null;
        }

        return (c);
    }
}

Related

  1. hexToColor(String hexString)
  2. hexToColor(String hexString)
  3. hexToColor(String input)
  4. hexToColor(String s)
  5. hexToColor(String string)