Getting Html color codes with a JColorChooser
Asked Answered
F

2

5

Is there a way to get the html color code from a JColorChooser

My java Applet takes three colors from the user and averages them and displays the color

I want to get the html color code after they look at the average color

how can I do that

Footwork answered 30/10, 2010 at 14:32 Comment(0)
E
7

Write a method to convert a Color to a String.

An HTML color code is just the R, G, and B values converted to hex and displayed as a string with a pound sign in front. This is a fairly simple method to write.

public static String toHexString(Color c) {
  StringBuilder sb = new StringBuilder("#");

  if (c.getRed() < 16) sb.append('0');
  sb.append(Integer.toHexString(c.getRed()));

  if (c.getGreen() < 16) sb.append('0');
  sb.append(Integer.toHexString(c.getGreen()));

  if (c.getBlue() < 16) sb.append('0');
  sb.append(Integer.toHexString(c.getBlue()));

  return sb.toString();
}
Embark answered 30/10, 2010 at 14:37 Comment(3)
new StringBuilder('#') ==> new StringBuilder("#")Maupin
@user249654 I didn't realize there wasn't a character constructor! I guess my code was just autoboxing it to a String. Thanks for the catch!Embark
@ErickRobertson +1 you can also use Color.getRGB() as described here.Kastner
K
1

A slightly shorter version that relies on Color.getRGB() :

public String color2HexString(Color color) {
    return "#" + Integer.toHexString(color.getRGB() & 0x00ffffff);
}

See Hex triplet for more information about Web colors.

Kastner answered 9/5, 2014 at 4:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.