Converts a Color to a hex color string. - Java 2D Graphics

Java examples for 2D Graphics:Color String

Description

Converts a Color to a hex color string.

Demo Code


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

public class Main {
    /**/*from  w ww  .j  a  v a2  s.c o m*/
     * Converts a Color to a hex color string. For example Color.GREEN will return "#00FF00".
     * @see java.awt.Color#decode(String) which does the opposite
     * @param color Color to encode
     * @return A hex Color string in the format #rrggbb. 
     */
    public static String encodeColor(Color color) {
        if (color == null) {
            //If no color, then return a middle-of-the-road gray.
            return "#808080";
        }
        return "#" + String.format("%06x", color.getRGB() & 0xffffff);

    }
}

Related Tutorials