Help with a Color Calculator in Java
I want to know how to paint the background based on the color of the hex value inputed by the user. I have this:
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);
}
}
But I want to know how to fix it such that incase the user decides to put a 0x in front of the hexadecimal code or not it will work. I also want to know how to convert the hex code into a color in java. I am having trouble with this.
This JUnit test may help you understand:
@Test
public void test1() {
Integer hexInt = Integer.parseInt("FF0000", 16);
Color createdColor = new Color(hexInt);
assertEquals(Color.RED, createdColor);
}
You can use Integer.parseInt
to turn the hexadecimal string into a number of base 16. Note this will throw an exception if the string is invalid (contains characters other than digits or a-f).
Color
instances can then be created using the Integer
.
I have included an assertion to show that the created is what we expect it to be.
Well, converting a hex-string into a Color:
Color myColor = Color.decode("0xFF0000");
Or you could do:
Color myColor2 = new Color(0xFF0000);
But then the input can't be a String, or else you'll get a NumberFormatException.
Figuring out if the input starts with an 0x should be easy
精彩评论