将RGB颜色值转换为hex

在我的Java应用程序中,我能够根据红色,绿色和蓝色值获得JButton颜色的值; 我已经将这些值存储为三个整数。

如何将RGB值转换为等效的hex值?

像这种格式的#0033fA

您可以使用

 String hex = String.format("#%02x%02x%02x", r, g, b); 

如果您希望得到的hex数字大写( #FFFFFF vs. #ffffff ),请使用大写X。

一个class轮,但没有String.format:

 Color your_color = Color.BLACK; String hex = "#"+Integer.toHexString(your_color.getRGB()).substring(2); 

如果要切换为大写字母,可以添加.toUpperCase()

 Random ra = new Random(); int r, g, b; r=ra.nextInt(255); g=ra.nextInt(255); b=ra.nextInt(255); Color color = new Color(r,g,b); String hex = Integer.toHexString(color.getRGB() & 0xffffff); if (hex.length() < 6) { hex = "0" + hex; } hex = "#" + hex; 

这是Vivien Barousse用Vulcan更新的答案的改编版本。 在这个例子中,我使用滑块dynamic检索三个滑块的RGB值,并在矩形中显示该颜色。 然后在方法toHex()我使用这些值来创build一个颜色,并显示相应的hex颜色代码。

此示例不包含GridBagLayout的正确约束。 虽然代码会起作用,但显示器看起来很奇怪。

 public class HexColor { public static void main (String[] args) { JSlider sRed = new JSlider(0,255,1); JSlider sGreen = new JSlider(0,255,1); JSlider sBlue = new JSlider(0,255,1); JLabel hexCode = new JLabel(); JPanel myPanel = new JPanel(); GridBagLayout layout = new GridBagLayout(); JFrame frame = new JFrame(); //set frame to organize components using GridBagLayout frame.setLayout(layout); //create gray filled rectangle myPanel.paintComponent(); myPanel.setBackground(Color.GRAY); //In practice this code is replicated and applied to sGreen and sBlue. //For the sake of brevity I only show sRed in this post. sRed.addChangeListener( new ChangeListener() { @Override public void stateChanged(ChangeEvent e){ myPanel.setBackground(changeColor()); myPanel.repaint(); hexCode.setText(toHex()); } } ); //add each component to JFrame frame.add(myPanel); frame.add(sRed); frame.add(sGreen); frame.add(sBlue); frame.add(hexCode); } //end of main //creates JPanel filled rectangle protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawRect(360, 300, 10, 10); g.fillRect(360, 300, 10, 10); } //changes the display color in JPanel private Color changeColor() { int r = sRed.getValue(); int b = sBlue.getValue(); int g = sGreen.getValue(); Color c; return c = new Color(r,g,b); } //Displays hex representation of displayed color private String toHex() { Integer r = sRed.getValue(); Integer g = sGreen.getValue(); Integer b = sBlue.getValue(); Color hC; hC = new Color(r,g,b); String hex = Integer.toHexString(hC.getRGB() & 0xffffff); while(hex.length() < 6){ hex = "0" + hex; } hex = "Hex Code: #" + hex; return hex; } } 

非常感谢Vivien和Vulcan。 这个解决scheme完美地工作,实现起来非常简单。