Java Swing issue - Using color palette

前端 未结 5 1923
南旧
南旧 2020-12-04 00:58

I have a problem here - I have a hexadecimal value being stored in a textfield after I have selected a color (using JColorChooser). What I would like to do is display the

5条回答
  •  伪装坚强ぢ
    2020-12-04 01:06

    I achieved this by Java Reflection : (works for static final Color defined in java.awt.Color)

    Here is my code :

    public static String getNameReflection(Color colorParam) {
            try {
                //first read all fields in array
                Field[] field = Class.forName("java.awt.Color").getDeclaredFields();
                for (Field f : field) {
                    String colorName = f.getName();
                    Class t = f.getType();
                    // System.out.println(f.getType());
                    // check only for constants - "public static final Color"
                    if (t == java.awt.Color.class) {
                        Color defined = (Color) f.get(null);
                        if (defined.equals(colorParam)) {
                            System.out.println(colorName);
                            return colorName.toUpperCase();
                        }
                    }
                }
            } catch (Exception e) {
                System.out.println("Error... " + e.toString());
            }
            return "NO_MATCH";
        }
    

    Source : http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/java-reflection-getting-name-of-color.html

提交回复
热议问题