Get a color from the user as a String and use it in a method that accepts enum values?

廉价感情. 提交于 2019-12-04 07:01:15

问题


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:


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.




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



回答3:


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.



来源:https://stackoverflow.com/questions/21103630/get-a-color-from-the-user-as-a-string-and-use-it-in-a-method-that-accepts-enum-v

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!