How to Create java.awt.Color From String Representation
Check out this post on how to create java.awt.Color from string representations using the Text-IO library. Click here to learn more.
Join the DZone community and get the full member experience.Join For Free
When using the Text-IO library, you can configure the text terminals via properties files. Colors can be specified using standard HTML names (e.g.
crimson), hex strings (e.g.
0xEE5533), rgb format strings (e.g.
rgba(112,25%,50%,0.9)), or hsl format strings (e.g.
How does Text-IO create colors from these string representations? Until recently, the implementation used the static method
web(String colorString) provided by
javafx.scene.Color. This method supports all the above mentioned formats and returns a
javafx.scene.Color instance. Text-IO needs a
java.awt.Color, but creating one from the returned
javafx.scene.Color is straightforward.
However, I was not happy with this solution. It made my code depend on JavaFX, although Text-IO doesn’t actually use JavaFX. And, starting with JDK 11, JavaFX is no longer part of the JDK.
So, I decided to write a little library named AWT Color Factory for creating
java.awt.Color objects from string representations. The simplest way to do this is to copy the code of the
javafx.scene.Color.web(String colorString) method and adapt it to create
But, what about licensing? JavaFX is released under the GPL, so my library must use the same license. Text-IO is, instead, released under the Apache-2.0 license. Is it then allowed to use my library? Yes, it is. The license under which JavaFX iwas released is actually not GPL but the GPL 2 with Classpath exception. The same applies to my library. This is very important, because the Classpath exception clause gives you permission to include the AWT Color Factory library in your executable code, regardless of the license under which your software is distributed.
AWT Color Factory is available in JCenter and Maven Central.
The library requires Java 7 or newer. The jar artifact is modularized under the name
Starting with version 3.2.0, Text-IO uses the AWT Color Factory library and no longer depends on JavaFX.
Published at DZone with permission of Serban Iordache, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.