Daniel Kats
Daniel Kats

Reputation: 5554

How To Print String representation of Color in Java

I have an array of colours of size n. In my program, the number of teams is always <= n, and I need to assign each team a unique color. This is my color array:

private static Color[] TEAM_COLORS = {Color.BLUE, Color.RED, Color.CYAN, Color.GREEN, Color.ORANGE, Color.PINK};

When I print information about the players in the console, I want to print what color is associated with them. When I print the color, I get

java.awt.Color[r=...,g=...,b=...]. 

I understand that this is how Java prints colours. I was wondering if there was a way to instead print BLUE, RED, etc. (so the pre-defined color string).

Upvotes: 0

Views: 15343

Answers (7)

silvalli
silvalli

Reputation: 315

  public static String colorToString(Color c) {
    if (c == null)  return "NullColor";
    for (var f : Color.class.getFields()) {
      if (f.getType() != Color.class)  continue;
      try {
        if (c.equals(f.get(null)))  return f.getName().toLowerCase();
      } catch (java.lang.IllegalAccessException e) {
        // Ignore. https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/reflect/Field.html#get(java.lang.Object)
      }
    }
    return c.toString();
  }

Upvotes: 0

havexz
havexz

Reputation: 9590

Extending @Jon_Skeet reply by adding name also to the enum.

public enum NamedColor {
  BLUE(Color.BLUE, "Blue"),
  RED(Color.RED, "Red"),
  ...;

  private final Color awtColor;
  private final String colorName;

  private NamedColor(Color awtColor, String name) {
    this.awtColor = awtColor;
    this.colorName = name;
  }

  public Color getAwtColor() {
    return awtColor;
  }

  public String getColorName() {
    return colorName;
  }
}

NOTE: IF voting this pls vote @Jon_Skeet reply too as it is extension of that...

Upvotes: 3

quantumSoup
quantumSoup

Reputation: 28132

Here's a Reflection-based approach:

public static String getColorName(Color c) {
    for (Field f : Color.class.getFields()) {
        try {
            if (f.getType() == Color.class && f.get(null).equals(c)) {
                return f.getName();
            }
        } catch (java.lang.IllegalAccessException e) {
            // it should never get to here
        } 
    }
    return "unknown";
}

Examples:

getColorName(Color.BLACK); // black
getColorName(Color.BLUE); // blue
getColorName(new Color(0,1,2)); // unknown

Demo: http://ideone.com/6cIBD


This will only work with colors defined as fields in java.awt.Color, namely: white, light gray, gray, dark gray, black, red, pink, orange, yellow, green, magenta, cyan and blue.

Upvotes: 3

ughzan
ughzan

Reputation: 1578

If you want your NamedColor to be used as a java.awt.Color and you don't have many colors you can extend it and store the name.

public class NamedColor extends java.awt.Color {

    private String name;

    public NamedColor(String name, java.awt.Color c) {
        super(c.getRGB());
        this.name = name;
    }

    public String toString() {
        return name;
    }
}

Upvotes: 1

Andrew Thompson
Andrew Thompson

Reputation: 168825

You might create a class that stores both a String representing the color name, as well as the Color itself.

Upvotes: 1

Rocky
Rocky

Reputation: 951

You can try using String.valueOf(color.getRGB())

Upvotes: -2

Jon Skeet
Jon Skeet

Reputation: 1500645

One option would be to create a NamedColor enum:

public enum NamedColor {
    BLUE(Color.BLUE),
    RED(Color.RED),
    ...;

    private final Color awtColor;

    private NamedColor(Color awtColor) {
        this.awtColor = awtColor;
    }

    public Color getAwtColor() {
        return awtColor;
    }
}

You'd then make your TEAM_COLORS array an array of NamedColor values instead of Color values, and fetch the AWT color when you need it. The default toString implementation of an enum is its name.

Another alternative would be to create your own Map<Color, String> and consult that when you need the string representation for a color.

Upvotes: 3

Related Questions