简体   繁体   English

为什么我不能用“new”关键字在Java中创建Color?

[英]Why can't I create a Color in Java with “new” keyword?

I was trying to make a new color in java using 我试图在java中使用一种新颜色

Color temp = new Color(foo.getBackground());

and it kept telling me cannot find symbol. 它一直告诉我找不到符号。

But this works 但这很有效

Color temp = (foo.getbackground());

Why? 为什么?

那是因为foo.getBackground()返回一个Color实例,并且没有Color构造函数将Color实例作为参数。

Check this link Color (Java 2 Platform SE v1.4.2) . 检查此链接Color(Java 2 Platform SE v1.4.2)

If you want this code to work: 如果您希望此代码有效:

Color temp = new Color(foo.getBackground());

foo.getBackground() must return an integer. foo.getBackground()必须返回一个整数。 Since it returns an object Color you have type mismatch. 由于它返回一个对象颜色,因此您的类型不匹配。

You can always do: 你可以随时做:

Color temp = new Color(foo.getbackground().getRGB());

or: 要么:

Color color = foo.getBackground();
Color temp = new Color(color.getRed(), color.getGreen(), color.getBlue(),color.getAlpha());

Yes, you can do it, the problem is that maybe foo.getBackground does'nt returns an integer or something similar. 是的,你可以做到,问题是foo.getBackground可能不会返回一个整数或类似的东西。

Color c = new Color(23,32,43)

works perfectly 工作得很好

There isn't a constructor for Color that takes just a Color. Color的构造函数不仅仅是一个Color。 In the second instance you're assigning a variable that was returned from a function. 在第二个实例中,您将分配从函数返回的变量。

The Color class does not have a constructor taking an other instance of Color as an argument, and that is what foo.getBackground() returns. Color类没有构造函数将Color的其他实例作为参数,这就是foo.getBackground()返回的内容。 IIRC, the Color class in Java is immutable - so there is simply no point in providing a constructor that would create a copy of an existing Color object. 在IIRC中,Java中的Color类是不可变的 - 因此提供一个可以创建现有Color对象副本的构造函数毫无意义。

Apparently the type that foo.getBackground() returns is of type "Color". 显然,foo.getBackground()返回的类型是“Color”类型。

While you can of course assign a Color to the variable temp of type Color, at least in java.awt.Color there is not constructor to create a Color from another Color. 虽然您可以将Color分配给Color类型的变量temp,但至少在java.awt.Color中没有构造函数可以从另一个Color创建Color。

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

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