How to get a color from the user as a String
and use it in a method that accepts Color enum
values?
The idea is to get a color that the user ch
I would create a Map<String, Color>
and populate it with what String
color names map to which Color
objects. You can use java.awt.Color's own static Color constants, e.g. colorMap.put("BLACK", Color.BLACK);
, or you can insert your own mappings. Then you can take the user input and perform a lookup with get
to get the proper Color
object needed.
If you're able to get the numeric value of the selected color and parse it into a String
then you can call Color.decode() method.
For instance white color:
element.setBackground(Color.decode("077777777")); // octal format
element.setBackground(Color.decode("0xFFFFFF")); // hexa format
element.setBackground(Color.decode("16777215")); // decimal format
From javadoc:
public static Color decode(String nm) throws NumberFormatException
Converts a String to an integer and returns the specified opaque Color. This method handles string formats that are used to represent octal and hexadecimal numbers.
Parameters:
nm
- a String that represents an opaque color as a 24-bit integerReturns: the new Color object.
This example uses the contents of a textField to set the color of the frame when a button is pressed
Field field = null;
try {
field = Color.class.getField(textField.getText().toString());
} catch (NoSuchFieldException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Color color = null;
try {
color = (Color)field.get(null);
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
frame.getContentPane().setBackground(color);