-1

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 chooses and pass the value (or handle the situation any other way) to a method element.setBackground(java.awt.Color).

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Mindaugas Bernatavičius
  • 3,757
  • 4
  • 31
  • 58
  • possible duplicate of [Converting a String to Color in Java](http://stackoverflow.com/questions/2854043/converting-a-string-to-color-in-java) – Jakub Kotowski Jan 14 '14 at 10:16

3 Answers3

3

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.

rgettman
  • 176,041
  • 30
  • 275
  • 357
2

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);
2

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 integer

Returns: the new Color object.

dic19
  • 17,821
  • 6
  • 40
  • 69