Returns a String of the form "#xxxxxx" good for use in HTML, representing the given color. - Java java.lang

Java examples for java.lang:String HTML

Description

Returns a String of the form "#xxxxxx" good for use in HTML, representing the given color.

Demo Code

/*//from   w  w w  .  jav  a  2 s.co m
 * 09/08/2005
 *
 * UIUtil.java - Utility methods for org.fife.ui classes.
 * Copyright (C) 2005 Robert Futrell
 * http://fifesoft.com/rtext
 * Licensed under a modified BSD license.
 * See the included license file for details.
 */
//package com.java2s;

import java.awt.Color;

public class Main {
    /**
     * Returns a <code>String</code> of the form "#xxxxxx" good for use
     * in HTML, representing the given color.
     *
     * @param color The color to get a string for.
     * @return The HTML form of the color.  If <code>color</code> is
     *         <code>null</code>, <code>#000000</code> is returned.
     */
    public static final String getHTMLFormatForColor(Color color) {

        if (color == null) {
            return "#000000";
        }

        StringBuilder sb = new StringBuilder("#");
        int r = color.getRed();
        if (r < 16) {
            sb.append('0');
        }
        sb.append(Integer.toHexString(r));

        int g = color.getGreen();
        if (g < 16) {
            sb.append('0');
        }
        sb.append(Integer.toHexString(g));

        int b = color.getBlue();
        if (b < 16) {
            sb.append('0');
        }
        sb.append(Integer.toHexString(b));

        return sb.toString();

    }
}

Related Tutorials