Converts a colour to it's RGB hex code - Java 2D Graphics

Java examples for 2D Graphics:Color

Description

Converts a colour to it's RGB hex code

Demo Code


//package com.java2s;

import javafx.scene.paint.Color;

public class Main {
    /**//ww  w .  jav  a 2 s  . c om
     * Converts a colour to it's RGB hex code
     * 
     * @param c
     * @return
     */
    public static String colorToHex(Color c) {
        String r = Integer.toHexString((int) (c.getRed() * 255));
        String g = Integer.toHexString((int) (c.getGreen() * 255));
        String b = Integer.toHexString((int) (c.getBlue() * 255));
        return "#" + (r.length() == 1 ? "0" + r : r)
                + (g.length() == 1 ? "0" + g : g)
                + (b.length() == 1 ? "0" + b : b);
    }
}

Related Tutorials