Search code examples
javaswingcolorshsvjcolorchooser

The JColorChooser represents Hue, Saturation, and Value as integers. How do I get these values from a Color object?


I am using a Java Swing JColorChooser in the HSV color space. This widget uses spinners to adjust the color. Hue is 0-360, Saturation is 0-100, and Value is 0-100. I am only able to get float values back though for the component values. I want to display the component values in a label after the user selects a color, but I can't figure out how to get the same values as are in the JColorChooser. My code:

private String getColorString(Color color)
{
    float[] comp = color.getColorComponents(chooser.getColorModel().getColorSpace(),
                                            null);

    return comp[0] + ", " + comp[1] + ", " + comp[2];
}

When my color chooser shows an HSV of 180,50,50 my component values are 0.24938,0.49749,0.49793

I realize that I am requesting a float array from the color, but there are no methods such as getHue().


Solution

  • To get HSB (same as HSV) from jColorChooser you can use Color.RGBtoHSB() in the following way.

    Color c = jColorChooser1.getColor();
    float[] comp = new float[3];
    Color.RGBtoHSB(c.getRed(), c.getGreen(), c.getBlue(), comp);
    comp[0]*= 360;
    comp[1]*= 100;
    comp[2]*= 100;
    return  comp[0]+", "+comp[1]+", "+comp[2];
    

    or in your method you can implement it like this

    private String getColorString(Color color)
    {
        float[] comp = new float[3];
        Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), comp);
        comp[0]*= 360;
        comp[1]*= 100;
        comp[2]*= 100;
        return  comp[0]+", "+comp[1]+", "+comp[2];
    }
    

    I know that there is a small difference in the value we give and in the value which is returned but you cannot go accurate more than this!