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

前端 未结 3 1032
长发绾君心
长发绾君心 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: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);
    

提交回复
热议问题