How To Print String representation of Color in Java

后端 未结 6 879
伪装坚强ぢ
伪装坚强ぢ 2020-12-20 10:12

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:

         


        
6条回答
  •  眼角桃花
    2020-12-20 10:49

    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 and consult that when you need the string representation for a color.

提交回复
热议问题