Zon
Zon

Reputation: 19880

How to get hex web String from JavaFX ColorPicker color?

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.

Upvotes: 15

Views: 26773

Answers (8)

Jeff E
Jeff E

Reputation: 688

I know it has been a while, but I found this method the ColorPicker[Skin] itself uses to display the value on the button: com.sun.javafx.scene.control.skin.Utils.formatHexString(Color c)

public static String formatHexString(Color c) {
    if (c != null) {
        return String.format((Locale) null, "#%02x%02x%02x",
                Math.round(c.getRed() * 255),
                Math.round(c.getGreen() * 255),
                Math.round(c.getBlue() * 255));
    } else {
        return null;
    }
}

Upvotes: 1

Zon
Zon

Reputation: 19880

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();

Upvotes: 2

DevProd_
DevProd_

Reputation: 41

this one worked for me

MyColorPicker.getValue().toString().substring(2)

Upvotes: -1

Kröw
Kröw

Reputation: 317

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.

Upvotes: 11

OpenRenaissance
OpenRenaissance

Reputation: 49

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!

Upvotes: 4

Marc
Marc

Reputation: 2639

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();
        }
    }

Upvotes: 2

Marcos Supridatta
Marcos Supridatta

Reputation: 161

I think that I have a better solution.

Hope it helps.

import javafx.scene.paint.Color;

/**
 *
 * @author Marcos Martinewski Alves
 */
public class ColorUtils {

    public static String colorToHex(Color color) {
        return colorChanelToHex(color.getRed())
                + colorChanelToHex(color.getGreen())
                + colorChanelToHex(color.getBlue())
                + colorChanelToHex(color.getOpacity());
    }

    private static String colorChanelToHex(double chanelValue) {
        String rtn = Integer.toHexString((int) Math.min(Math.round(chanelValue * 255), 255));
        if (rtn.length() == 1) {
            rtn = "0" + rtn;
        }
        return rtn;
    }

}

Upvotes: 0

Moe
Moe

Reputation: 584

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 ) );
    }
}

Upvotes: 44

Related Questions