Getting Html color codes with a JColorChooser

自作多情 提交于 2019-12-23 14:14:47

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/4059133/getting-html-color-codes-with-a-jcolorchooser

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!