How to get hex web String from JavaFX ColorPicker color?


Question

I have Color chosen in JavaFX ColorPicker. Now I need to save it as hex string. I found this method, but for JavaFX it is not applicable. JavaFX has its own Color class without getRGB() method, that could be used as mediatory convertion.

1
9
7/30/2013 12:28:12 PM

Accepted Answer

This does the trick:

// 8 symbols.
String hex1 = Integer.toHexString(myColorPicker.getValue().hashCode()); 

// With # prefix.
String hex2 = "#" + Integer.toHexString(myColorPicker.getValue().hashCode()); 

// 6 symbols in capital letters.
String hex3 = Integer.toHexString(myColorPicker.getValue().hashCode()).substring(0, 6).toUpperCase();
2
7/30/2013 12:15:07 PM

Translate a color into a web color code:

public class FxUtils
{
    public static String toRGBCode( Color color )
    {
        return String.format( "#%02X%02X%02X",
            (int)( color.getRed() * 255 ),
            (int)( color.getGreen() * 255 ),
            (int)( color.getBlue() * 255 ) );
    }
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon