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

前端 未结 3 1024
长发绾君心
长发绾君心 2021-01-29 10:00

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

相关标签:
3条回答
  • 2021-01-29 10:15

    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.

    0 讨论(0)
  • 2021-01-29 10:25

    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.

    0 讨论(0)
  • 2021-01-29 10:26

    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);
    
    0 讨论(0)
提交回复
热议问题