0

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

Justin Wiseman
  • 780
  • 1
  • 8
  • 27

2 Answers2

2

Call Color.RGBtoHSB() using the RGB components of the Color obtained from the chooser, as shown here.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
2

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!

MMujtabaRoohani
  • 483
  • 4
  • 19
  • Thanks. By rounding the returned values to whole ints, I was able to get very close. Occasionally though the numbers did not match the chooser controls. This is unfortunate. My users don't really need to know the component values, so I am going to just represent the selection as a colored icon on the button that launches the JColorChooser. – Justin Wiseman Aug 12 '13 at 14:51
  • Yeah I knew that Rounding those values cannot solve the problem that's why I said it's the most accurate we can get. – MMujtabaRoohani Aug 12 '13 at 14:55
  • This does not work if value and saturation are zero. E.g. if you choose (h,s,v) = (42,0,0) the JColorChooser will return (r,g,b) = (0,0,0) and Color.RGBtoHSB will turn it into (h,s,v) = (0, 0, 0). There are some corner cases where this is important, e.g. if you want to do color interpolation in hsv. – Arne Böckmann Dec 29 '15 at 21:18