在Java中给定Color对象获取相应的hex颜色代码的方法?

我已经检查了Color的Java类文档,发现我可以使用Color.decode();从hex代码字符串(eg "#FFFFFF")生成一个Color对象Color.decode(); 方法。

我想为我正在处理的项目实现反向过程,但似乎没有为此类内置的方法。

是否有捷径可寻?

 String.format("#%06x", color.getRGB() & 0x00FFFFFF) 

掩码用于在位24-31中移除α分量

 Color color = Color.BLUE; Formatter f = new Formatter(new StringBuffer("#")); f.format("%02X", color.getRed()); f.format("%02X", color.getGreen()); f.format("%02X", color.getBlue()); f.toString(); //#0000FF 

阅读: 使用JColorChooser获取Html颜色代码

答案有一种方法可以将颜色转换为hex值。

还有另一种方式。 以为我只是添加了这个选择。

 // ARGB = (255, 255, 0, 0) (Red) // hex -> "ffff0000" String hex = Integer.toHexString(color.getRGB()); // Reduced to RGB: hex -> "#ff0000" hex = "#" + hex.substring(2, hex.length());