Converts the specified rgb values to a hexadecimal representation. - Java 2D Graphics

Java examples for 2D Graphics:Color RGB

Description

Converts the specified rgb values to a hexadecimal representation.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        int r = 2;
        int g = 2;
        int b = 2;
        System.out.println(toHex(r, g, b));
    }//from   w  w  w .j av  a  2 s.co m

    /**
     * Converts the specified rgb values to a hexadecimal representation.
     * 
     * @param r
     *            red
     * @param g
     *            green
     * @param b
     *            blue
     * @return hexadecimal representation of the color
     */
    public static String toHex(int r, int g, int b) {
        return "#" + number2hex(r) + number2hex(g) + number2hex(b);
    }

    private static String number2hex(int nr) {
        String hex = Integer.toHexString(nr);

        String result = hex;

        while (result.length() < 2) {
            result = '0' + result;
        }

        return result;
    }
}

Related Tutorials