locho30
locho30

Reputation: 15

Java : Convert Color string value to Hexa value

I am trying to change color value to color hexa code. So, I code like this:

color = Integer.toHexString(colorpick.getValue().hashCode()).substring(0, 6).toUpperCase();

The above code is Ok for all colors except for "Black" color.

It gives the following error for "Black" color.

String index out of range : 6 error

Is any solution for my problem, please?

Upvotes: 0

Views: 980

Answers (3)

KC Wong
KC Wong

Reputation: 2479

Since you did not mention what class the variable "colorpick" is, I'm going to assume it's ColorPicker (https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ColorPicker.html).

I don't think its hashcode() method is overriden to return the RGB value in hex.

The cause of your error is that black's RGB value is 0. Applying .toHexString() will only give you "0", a single character, hence the .substring() will not work. Other RGB values may also result in a string shorter than 6.

I assume you want the result to be always 6-digit; then you should pad the string with 0 from the start if it's shorter.

Edit ColorPicker.getValue() returns a Color object, not the RGB value. So you should use colorpick.getValue().getRGB() instead.

https://docs.oracle.com/javase/7/docs/api/java/awt/Color.html#getRGB()

Edit2
With and without .getRGB():

Color c = Color.CYAN;
String s = Integer.toHexString(c.getRGB() & 0xFFFFFF).toUpperCase();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 6 - s.length(); i++) {
    sb.append("0");
}
sb.append(s);
System.out.println(sb.toString());

Color c = Color.CYAN;
int rgbValue = (c.getRed() << 16) + (c.getGreen() << 8) + c.getBlue();
String s = Integer.toHexString(rgbValue & 0xFFFFFF).toUpperCase();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 6 - s.length(); i++) {
    sb.append("0");
}
sb.append(s);
System.out.println(sb.toString());

Upvotes: 1

Nugroho Prayogo
Nugroho Prayogo

Reputation: 1

use try catch function to handle it. if error hexa

Upvotes: 0

this is absolutely wrong here:

colorpick.getValue().hashCode()

hashcode is a specific code generated by the JVM to manage hash numbers related to instances and hash-tables... and has NOTHING to do with colors..

this should be more than ok

colorpick.getValue()

Upvotes: 2

Related Questions