在我的Java应用程序中,我能够以红色,绿色和蓝色的形式获得Color
的JButton
;我已将这些值存储在三个int
s中。
如何将这些RGB值转换为包含等效十六进制值的String
?
一个例子是"#0033fA"
您可以使用
String hex = String.format("#%02x%02x%02x", r, g, b);
如果您希望得到的十六进制数字大写(#FFFFFF
vs. #ffffff
),请使用大写X.
一个内衬但没有String.format:
Color your_color = Color.BLACK;
String hex = "#"+Integer.toHexString(your_color.getRGB()).substring(2);
您可以添加要切换为大写字母的.toUpperCase()
if。
请注意,ARRG是正确的 - 仅用于非透明颜色。
if(your_color.getAlpha() >= 16){
String hex = "#"+Integer.toHexString(your_color.getRGB()).substring(2);
}
else{...}
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的更新。在这个例子中,我使用滑块动态地从三个滑块中检索RGB值,并在矩形中显示该颜色。然后在方法toHex()中,我使用这些值来创建颜色并显示相应的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。该解决方案完美无缺,实施起来非常简单。