How To Get The Hex Value From Color

4 years ago by in AWT, How To Tagged: , , , , , ,

To convert a Color into the HEX equivalent we can use the following utility function.

public final static String toHexString(Color colour) throws NullPointerException {
  String hexColour = Integer.toHexString(colour.getRGB() & 0xffffff);
  if (hexColour.length() < 6) {
    hexColour = "000000".substring(0, 6 - hexColour.length()) + hexColour;
  }
  return "#" + hexColour;
}

The given colour cannot be null, as otherwise an NullPointerException is thrown.

In order to create a Color object out of the HEX string, use the decode() method as shown next.

Color color = Color.decode("#FF0000");
Albert Attard

Albert Attard is a Java passionate and technical lead at a research group. You can find him on . Over the past years Albert worked on various Java projects including traditional server/client applications, modular applications, large data handling applications and concurrent data manipulation applications to name a few. He has a BSc degree from the University of London (Homepage) and an MSc Information Security with the same university. His MSc thesis (Book) received the 2012 SearchSecurity.co.UK award (Website).

One Response to “How To Get The Hex Value From Color”


Nick
February 2, 2016 Reply

Thanks for the information!

Leave a Comment