gpt4 book ai didi

java - Java 颜色计算器帮助

转载 作者:行者123 更新时间:2023-12-01 16:01:12 25 4
gpt4 key购买 nike

我想知道如何根据用户输入的十六进制值的颜色来绘制背景。我有这个:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class SimpleColorCalc extends JFrame implements Runnable
{
ColorPanel cp;
JButton show;
JTextField hexCode;

public SimpleColorCalc()
{
super("Simple Color Calculator");
cp = new ColorPanel();
show = new JButton("Show the Color");
hexCode = new JTextField("ffffff");
show.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String text = hexCode.getText();
try
{
int colorCode = Integer.parseInt(text, 16);
Color enteredColor = new Color(colorCode);
cp.setColor(enteredColor);
}
catch(NumberFormatException ex)
{
hexCode.setText("ffffff");
cp.setColor(Color.white);
}
finally
{
repaint();
}
}
});
}
public static void main(String[] args)
{
SimpleColorCalc scc = new SimpleColorCalc();
javax.swing.SwingUtilities.invokeLater(scc);
}
public void run()
{
setSize(400,300);
Container c = getContentPane();
JPanel top = new JPanel();
c.add(BorderLayout.NORTH, top);
top.setLayout(new GridLayout(1,2));
top.add(show);
top.add(hexCode);
setVisible(true);
}
}

但我想知道如何修复它,以便万一用户决定在十六进制代码前面放置 0x 或不将其工作。我还想知道如何在java中将十六进制代码转换为颜色。我在这方面遇到了麻烦。

最佳答案

这个 JUnit 测试可以帮助您理解:

@Test
public void test1() {
Integer hexInt = Integer.parseInt("FF0000", 16);
Color createdColor = new Color(hexInt);
assertEquals(Color.RED, createdColor);
}

您可以使用Integer.parseInt将十六进制字符串转换为以16为基数的数字。请注意,如果字符串无效(包含数字或a-f以外的字符),这将引发异常。

然后可以使用 Integer创建

Color实例。

我添加了一个断言来表明创建的内容正是我们所期望的。

关于java - Java 颜色计算器帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3842994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com