简体   繁体   English

如何将字符串转换为const类的int值?

[英]How can I convert string to const class int value?

I have variable: 我有变量:

String colorName = "BLUE";

I want to set this color to the paint in android application. 我想将此颜色设置为android应用程序中的paint。 It should be something like this: 它应该是这样的:

paint.setColor ("Color." + colorName);

But I receive the error warning because argument for setColor() function should be int. 但是我收到错误警告,因为setColor()函数的参数应该是int。 Any ideas?Thanks. 有什么想法?谢谢。

你需要这样做:

paint.setColor(Color.BLUE);

Try this: 尝试这个:

protected static final int colorName = Color.BLUE;
paint.setColor(colorName);

EDIT: as i see, you get your Color as a string. 编辑:正如我所见,你将你的颜色作为一个字符串。 So you have to check, what color it is and then set your 'colorName' variable. 所以你必须检查它是什么颜色,然后设置'colorName'变量。 Something like this: 像这样的东西:

if(yourcolorstring.equals("Blue")){
     colorName = Color.BLUE;
}else if(yourcolorstring.equals("Black")){
     colorName = Color.BLACK;
}else{
     colorName = Color.WHITE;
}

If you have a long list of colors and you don't want to write a long sequence of if ... else if statements, you could also use a Map for this. 如果您有很长的颜色列表,并且您不想编写if ... else if语句的长序列, if您也可以使用Map来实现。 The key would be the string with the name of the color, the value the Color constant value that you want to find. 键是具有颜色名称的字符串,值是您要查找的Color常量值。 Example: 例:

Map<String, Color> colors = new HashMap<String, Color>();
colors.put("BLUE", Color.BLUE);
colors.put("RED", Color.RED);
colors.put("GREEN", Color.GREEN);

// To find the Color constant, look it up in the map:
String text = "BLUE";
Color c = colors.get(text);
if (c != null) {
    paint.setColor(c);
} else {
    System.out.println("Unknown color: " + text);
}

At least in standard Java one can use: 至少在标准Java中可以使用:

import javax.swing.text.html.CSS;

String colorName = "fuchsia"; // "maroon", "rgb(1,20,30)", "#ff00aa"
Color color = CSS.stringToColor(colorName);

This is because of the HTML support; 这是因为HTML支持; you may also write a JLabel with 你也可以写一个JLabel

"<html><span style='color:blue'>hello</span>"

JDK 7 of Oracle To show what text constants are feasible and what formats: Oracle的JDK 7要显示哪些文本常量可行以及哪些格式:

 /**
  * Convert a "#FFFFFF" hex string to a Color.
  * If the color specification is bad, an attempt
  * will be made to fix it up.
  */
static final Color hexToColor(String value) {
    String digits;
    int n = value.length();
    if (value.startsWith("#")) {
        digits = value.substring(1, Math.min(value.length(), 7));
    } else {
        digits = value;
    }
    String hstr = "0x" + digits;
    Color c;
    try {
        c = Color.decode(hstr);
    } catch (NumberFormatException nfe) {
        c = null;
    }
     return c;
 }

/**
 * Convert a color string such as "RED" or "#NNNNNN" or "rgb(r, g, b)"
 * to a Color.
 */
static Color stringToColor(String str) {
  Color color;

  if (str == null) {
      return null;
  }
  if (str.length() == 0)
    color = Color.black;
  else if (str.startsWith("rgb(")) {
      color = parseRGB(str);
  }
  else if (str.charAt(0) == '#')
    color = hexToColor(str);
  else if (str.equalsIgnoreCase("Black"))
    color = hexToColor("#000000");
  else if(str.equalsIgnoreCase("Silver"))
    color = hexToColor("#C0C0C0");
  else if(str.equalsIgnoreCase("Gray"))
    color = hexToColor("#808080");
  else if(str.equalsIgnoreCase("White"))
    color = hexToColor("#FFFFFF");
  else if(str.equalsIgnoreCase("Maroon"))
    color = hexToColor("#800000");
  else if(str.equalsIgnoreCase("Red"))
    color = hexToColor("#FF0000");
  else if(str.equalsIgnoreCase("Purple"))
    color = hexToColor("#800080");
  else if(str.equalsIgnoreCase("Fuchsia"))
    color = hexToColor("#FF00FF");
  else if(str.equalsIgnoreCase("Green"))
    color = hexToColor("#008000");
  else if(str.equalsIgnoreCase("Lime"))
    color = hexToColor("#00FF00");
  else if(str.equalsIgnoreCase("Olive"))
    color = hexToColor("#808000");
  else if(str.equalsIgnoreCase("Yellow"))
    color = hexToColor("#FFFF00");
  else if(str.equalsIgnoreCase("Navy"))
    color = hexToColor("#000080");
  else if(str.equalsIgnoreCase("Blue"))
    color = hexToColor("#0000FF");
  else if(str.equalsIgnoreCase("Teal"))
    color = hexToColor("#008080");
  else if(str.equalsIgnoreCase("Aqua"))
    color = hexToColor("#00FFFF");
  else if(str.equalsIgnoreCase("Orange"))
    color = hexToColor("#FF8000");
  else
      color = hexToColor(str); // sometimes get specified without leading #
  return color;
}

/**
 * Parses a String in the format <code>rgb(r, g, b)</code> where
 * each of the Color components is either an integer, or a floating number
 * with a % after indicating a percentage value of 255. Values are
 * constrained to fit with 0-255. The resulting Color is returned.
 */
private static Color parseRGB(String string) {
    // Find the next numeric char
    int[] index = new int[1];

    index[0] = 4;
    int red = getColorComponent(string, index);
    int green = getColorComponent(string, index);
    int blue = getColorComponent(string, index);

    return new Color(red, green, blue);
}

/**
 * Returns the next integer value from <code>string</code> starting
 * at <code>index[0]</code>. The value can either can an integer, or
 * a percentage (floating number ending with %), in which case it is
 * multiplied by 255.
 */
private static int getColorComponent(String string, int[] index) {
    int length = string.length();
    char aChar;

    // Skip non-decimal chars
    while(index[0] < length && (aChar = string.charAt(index[0])) != '-' &&
          !Character.isDigit(aChar) && aChar != '.') {
        index[0]++;
    }

    int start = index[0];

    if (start < length && string.charAt(index[0]) == '-') {
        index[0]++;
    }
    while(index[0] < length &&
                     Character.isDigit(string.charAt(index[0]))) {
        index[0]++;
    }
    if (index[0] < length && string.charAt(index[0]) == '.') {
        // Decimal value
        index[0]++;
        while(index[0] < length &&
              Character.isDigit(string.charAt(index[0]))) {
            index[0]++;
        }
    }
    if (start != index[0]) {
        try {
            float value = Float.parseFloat(string.substring
                                           (start, index[0]));

            if (index[0] < length && string.charAt(index[0]) == '%') {
                index[0]++;
                value = value * 255f / 100f;
            }
            return Math.min(255, Math.max(0, (int)value));
        } catch (NumberFormatException nfe) {
            // Treat as 0
        }
    }
    return 0;
}

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

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