Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

tostring - 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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...