简体   繁体   English

java.awt.color返回颜色名称而不是RGB值

[英]java.awt.color return color name not RGB value

Before anyone marks this as a duplicate, I read about 7 other questions that were similar and none of them had answers anywhere close to what I'm looking for. 在有人将此标记为重复之前,我读了大约7个其他相似的问题,但没有一个答案接近我要寻找的答案。 I also ventured past the first two pages of Google search results and still couldn't find an answer. 我还冒险浏览了Google搜索结果的前两页,但仍然找不到答案。

I don't care about all the colors in the world, I just want to use the ones that are already in the java Color class (ie "red", "black", "green"). 我并不关心世界上所有的颜色,我只想使用java Color类中已经存在的颜色(即“红色”,“黑色”,“绿色”)。

I'm writing a program for an intro Java class and the professor said to declare "a private Color data field named guitarColor that defines the color of the guitar. The default value should be Color.Red." 我正在为Java入门类编写程序,这位教授说要声明“一个名为GuitarColor的私有Color数据字段,它定义吉他的颜色。默认值应为Color.Red。” His example output shows the color returning as "getColor(): Red". 他的示例输出显示颜色返回为“ getColor():红色”。 So I need to use the color class to get the output in this format. 所以我需要使用颜色类来获取这种格式的输出。

When I use the java.awt.color class and input something like Color.RED, I want it to return "Red", not "java.awt.Color[r=255,g=0,b=0]". 当我使用java.awt.color类并输入类似于Color.RED的内容时,我希望它返回“ Red”,而不是“ java.awt.Color [r = 255,g = 0,b = 0]”。 How can I do this? 我怎样才能做到这一点?

import java.awt.Color;

public class Program
{
    public static void main(String[] args) {

    Guitar g1 = new Guitar(); 

    System.out.println("getColor() result: " + g1.getColor());

    }
}


public class Guitar {    

    private Color guitarColor;

    public Guitar () {
        guitarColor = Color.RED;
    }

   public Color getColor() {
       return guitarColor;
   }


} 

Output: 输出:

getColor() result: java.awt.Color[r=255,g=0,b=0]

I would create a function in the guitar class that deciphers what color the guitar is and returns the String representation of that color and not the actual Color object. 我将在Guitar类中创建一个函数,该函数可解密吉他的颜色,并返回该颜色的String表示形式,而不是实际的Color对象。 Try this 尝试这个

public String getColorOfGuitar() {

    if(guitarColor.equals(Color.RED))
        return "RED";
    else if(guitarColor.equals(Color.BLUE))
        return "BLUE";
    else if(guitarColor.equals(Color.YELLOW))
        return "YELLOW";
    else
        return "Unknown Color";
}

Now when you call the method it will return a String representation of that Color 现在,当您调用该方法时,它将返回该颜色的字符串表示形式

System.out.println("getColorOfGuitar() result: " + g1.getColorOfGuitar()); //--> getColor() result: RED

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

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