-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).

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

2 Comments

Sorry, but this is user unfriendly solution. Only natural language inputs should be used.
No problem but consider add this in your questions as this is very relevant to your requirements. @MindaugasBernatavičius

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.