Java 使用这样的变量:set.color(Color.variable)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19734981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:48:52  来源:igfitidea点击:

Use a variable like this: set.color(Color.variable)

javastringvariablescolors

提问by Chronicle

In this method I make a string variable, and move it to a different one.

在这种方法中,我创建了一个字符串变量,并将其移动到另一个变量中。

    private void produceRainbow() {
       String color = "RED";
       produceArc(color);
    }

There is more code there but it does not matter (essentially, changing the string to other colors).

那里有更多代码,但这并不重要(本质上,将字符串更改为其他颜色)。

Next this method:

接下来这个方法:

private void produceArc(String color) {
    GOval arc = new GOval(leftX, upperY, rightX, lowerY); 
    arc.setColor(Color.color);
}

(Ignore the variables leftX, upperY, rightX, lowerY)

(忽略变量 leftX、upperY、rightX、lowerY)

Here I want to set the color to a string. So I want it to become arc.setColor(Color.RED)

在这里,我想将颜色设置为字符串。所以我想让它变成arc.setColor(Color.RED)

When I compile, I get this error:

当我编译时,我收到此错误:

Program.java:89: cannot find symbol
symbol  : variable color
location: class java.awt.Color
    arc.setColor(Color.color);

Is it even possible to do what I want to do? If so, what am I doing wrong?

甚至有可能做我想做的事吗?如果是这样,我做错了什么?

(If you're curious, I made a seperate method for each arc (red, blue, green, etc, all have their own method) and this works, but I was wondering if I could just use one method that takes a variable, which makes the code a lot shorter)

(如果你很好奇,我为每个弧(红色、蓝色、绿色等,都有自己的方法)制作了一个单独的方法,这有效,但我想知道我是否可以只使用一种带有变量的方法,这使得代码更短)

采纳答案by James

To elaborate the comment I gave.

详细说明我给出的评论。

You could either pass the Color.RED right away or use Color.FromName(string name);

您可以立即传递 Color.RED 或使用 Color.FromName(string name);

Suggested method:

建议方法:

To pass the Color.RED your methods will look like this:

要传递 Color.RED,您的方法将如下所示:

private void produceRainbow() {
       Color color = Color.RED;
       produceArc(color);
    }

And:

和:

private void produceArc(Color color) {
    GOval arc = new GOval(leftX, upperY, rightX, lowerY); 
    arc.setColor(color);
}

Method 2

方法二

If, for some reason, you would use the FromName method you'd apply it like below:

如果出于某种原因,您将使用 FromName 方法,您将像下面这样应用它:

private void produceRainbow() {
       String color = "Red";
       produceArc(color);
    }

And:

和:

private void produceArc(String color) {
    GOval arc = new GOval(leftX, upperY, rightX, lowerY); 
    arc.setColor(Color.FromName(color));
}

Note that this last method is only working in C# and is not suitable for Java. (I'm not sure whether you're using Java or C#)

请注意,最后一种方法仅适用于 C#,不适用于 Java。(我不确定您使用的是 Java 还是 C#)