How to get hex web String from JavaFX ColorPicker color?
Solution 1
This fragile solution does the trick perfectly:
// 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();
Solution 2
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 ) );
}
}
Solution 3
A floating point safe method:
// Helper method
private String format(double val) {
String in = Integer.toHexString((int) Math.round(val * 255));
return in.length() == 1 ? "0" + in : in;
}
public String toHexString(Color value) {
return "#" + (format(value.getRed()) + format(value.getGreen()) + format(value.getBlue()) + format(value.getOpacity()))
.toUpperCase();
}
The currently top voted answer isn't actually safe for many possible Color
objects due to floating point representation and casting. Using Math.round(...)
fixes this.
I was generating Color
objects using random doubles (from Math.random()
) with the Color.hsb(...)
method. Without using Math.round()
, the converted hexadecimal codes were off. If you're taking a similar approach to generating your colors, this method is suggested, as it is all around more safe.
Solution 4
The currently accepted answer of
return String.format("#%02X%02X%02X",
((int)color.getRed())*255,
((int)color.getGreen())*255,
((int)color.getBlue())*255);
The most working answer among the ones currently available is Zon's (below for reference)
// 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();
However this method runs into the issue of automatic removal of beginning zeros. If a color's hex values begin with 0's (eg #000000, #00A3FF, etc) the begining zeros will be automatically removed, leaving the string too short to function fully as a hex code. Color.BLACK produces hex "#FF" as it only maintains its opacity. The method below, as of JavaFX 8u112 fully solves the color to hex conversion.
String colorToHex(Color color) {
String hex1;
String hex2;
hex1 = Integer.toHexString(color.hashCode()).toUpperCase();
switch (hex1.length()) {
case 2:
hex2 = "000000";
break;
case 3:
hex2 = String.format("00000%s", hex1.substring(0,1));
break;
case 4:
hex2 = String.format("0000%s", hex1.substring(0,2));
break;
case 5:
hex2 = String.format("000%s", hex1.substring(0,3));
break;
case 6:
hex2 = String.format("00%s", hex1.substring(0,4));
break;
case 7:
hex2 = String.format("0%s", hex1.substring(0,5));
break;
default:
hex2 = hex1.substring(0, 6);
}
return hex2;
}
Hope this saves someone the trouble I went through!
Solution 5
You can use the getGreen()
, getBlue()
, getRed()
methods and convert it to hex.
Color c;
int green = c.getGreen()*255;
Integer.toHexString(green);
repeat this for red and blue then :
String hexColor = "#"+red+green+blue;
This is the idea, the complete code (copy-pastable) :
public class TestColor {
public TestColor() {
Color c = Color.ALICEBLUE;
int green = (int) (c.getGreen()*255);
String greenString = Integer.toHexString(green);
int red = (int) (c.getRed()*255);
String redString = Integer.toHexString(red);
int blue = (int) (c.getBlue()*255);
String blueString = Integer.toHexString(blue);
String hexColor = "#"+redString+greenString+blueString;
System.out.println(hexColor);
System.out.println(c.toString());
}
public static void main(String[] args) {
new TestColor();
}
}
Zon
Senior Java Software Engineer. Production-grade scalable services using: Domain-Driven Design Command-Query Responsibility Segregation Event-Sourcing Microservices You can contact me at LinkedIn.
Updated on September 12, 2020Comments
-
Zon over 3 years
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.
-
Dragon over 10 yearsThe only variant among answers here that works fine without exceptions for black and other simple colors.
-
Balage1551 almost 10 yearsThis is a fragile solution. the generation of hash code is implementation dependent, so it is not ensured that in later releases it would work. (For example, if another field is included to the hash code such as opacy.)
-
Neuron almost 8 yearsthis doesnt work. If any component is zero, it will just be
0
instead of00
-
mid over 6 yearsYour first solution produces only zeroes on every Java version because casting has a higher precedence, thus you are basically always multiplying
0 * 255
-
hrabinowitz over 5 yearsnot wise to rely on the implementation of hashCode(), since the implementation is not specified in the API.
-
Kröw almost 5 yearsThis method is unsafe for many possible
Color
values due to floating point representations. See this answer for details. -
Nick about 4 yearsCode only answers are discouraged. Please add some explanation as to how this solves the problem, or how this differs from the existing answers. From Review
-
DevProd_ about 4 yearsyou can use like this : String hexcolor = MyColorPicker.getValue().toString().substring(2); what i'm saying that when you want to get the value of ColorPicker as a string you try this bcz the get getValue() wil return the value started with 0x.... and substring(2) wil remove that 0x so you get the right value of the color
-
kleopatra about 4 yearsno, relying on
whatEverObject.toString()
is wrong, always -
Martin819 about 2 yearsAgree @mid, the typecasting has to performed only after the multiplication by 255. So the final solution will be
(int) (color.get().getRed() * 255)