21

this article suggests you can use Color c = Color.decode("FF0096"); however this understandably throws an exception

Caused by: java.lang.NumberFormatException: For input string: "FF0096"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Integer.parseInt(Integer.java:449)
    at java.lang.Integer.valueOf(Integer.java:528)
    at java.lang.Integer.decode(Integer.java:958)
    at java.awt.Color.decode(Color.java:707)

What is the best way of converting a String in the format of "#FF0096" or "FF0096" into a java awt Color?

3 Answers 3

50
Color c = Color.decode("0xFF0096");

or

Color c = Color.decode("#FF0096");

or

Color c = new Color(0xFF0096);
Sign up to request clarification or add additional context in comments.

1 Comment

6 hex digits max! I could not specify alpha.
9

The Color.decode method throws the NumberFormatException if the specified string cannot be interpreted as a decimal, octal, or hexidecimal integer

The string "FF0096" without the prefix of 0 or 0x will be interpreted as a base 10 representation which does not work.

3 Comments

you are wrong to say that FF0096 prefixed with 0x does not work.
@pstanton: Thanks for pointing out..it was a typo. I've corrected it.
0 prefix means octal and it's very unlikely anyone would like that for decoding colors
2

I was looking for a similar way to do this in Android. For some reason, I couldn't find Color.decode() so I looked for an alternative. If you want to use a hex string to represent a color in Android, you can do the following:

String hexColor = "#142b44";
View row = findViewById(R.id.row);
int color = Color.parseColor(hexColor);
row0.setBackgroundColor(color);

More at Color#parseColor

1 Comment

This question is about java.awt.Color, while you're using android.graphics.Color.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.