简体   繁体   English

更改面板颜色

[英]changing panel color

i have a string which stores the name of a color. 我有一个存储颜色名称的字符串。 Through the help of this variable i need to change the panel background. 通过此变量,我需要更改面板背景。 how can it be done??? 如何做呢???

Create Map which contains the String name of the color and the actual Color object. 创建包含颜色的字符串名称和实际Color对象的Map。

Edit: 编辑:

Just noticed two other answers suggest using the getColor(...) method. 刚刚注意到另外两个答案建议使用getColor(...)方法。 That does not just magically work and you need to define the color in the system properties. 这不仅神奇地起作用,而且您需要在系统属性中定义颜色。 I've never used system properties, but I believe you need to set them when you start the JVM. 我从未使用过系统属性,但是我相信您在启动JVM时需要设置它们。

If the colors are only going to be the ones that java supports, you could do something like the following: 如果颜色仅是Java支持的颜色,则可以执行以下操作:

private Color getColorByName(String colorName) {

    Field[] colorFields = Color.class.getDeclaredFields();
    for (Field field : colorFields) {
        if (field.getName().equals(colorName.toUpper())) {
            //check that this is in fact a static field,
            //to make sure it is one of the colors you are looking for
            int modifiers = field.getModifiers();
            if ((Modifiers.STATIC & modifiers != 0) 
                    && (Modifiers.PUBLIC & modifiers != 0)) {
                try{
                    return (Color)field.getValue(null);
                } catch (FieldNotFoundException ex) {
                    //Maybe put some additional handling in here if you need it
                }
            }
        }
    }
    //or return a default color
    return null;
}

A few notes: 一些注意事项:

  1. This uses reflection, so it will be slower (although you could, technically use this to make a color map at startup of the application and just reference that). 这会使用反射,因此会变慢(尽管可以,但从技术上讲,可以在应用程序启动时使用它来制作颜色图,并仅引用它即可)。
  2. It would make a lot more sense to make a color map as mentioned by other people above. 如上面的其他人所提到的,制作彩色图会更有意义。

  3. The best would be if the different systems sent you actual values - say rgb values in int or 0.0-1.0 double format. 最好的办法是,如果不同的系统向您发送了实际值,例如int或0.0-1.0 double格式的rgb值。 Then you could consistently give them the appropriate response. 然后,您可以始终如一地给他们适当的答复。

My recommendation, if you must use the color name, would be that they give you a set of names you must support, and you have an error condition - either a default color, null, or throw an exception. 我的建议(如果必须使用颜色名称)将是它们为您提供一组必须支持的名称,并且您有一个错误条件-默认颜色,空值或引发异常。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM