简体   繁体   English

Java newColor构造函数随机化

[英]Java newColor constructor randomized

I am having a problem making a new Color that will be random in Java. 我在制作将在Java中为随机的新颜色时遇到问题。 I get a syntax error saying that double, double, double is not how you define a new color. 我收到语法错误,说double,double,double不是您定义新颜色的方式。 How would I accomplish this? 我将如何完成? Anyways, here is the code that is giving me the trouble. 无论如何,这是给我带来麻烦的代码。

  double colorCode = (double) (Math.random());

  double r = colorCode % 255;
  double g = (colorCode*2) % 255;
  double b = (colorCode+128) % 255;

  page.setColor(new Color(r,g,b);

The error you are getting is because Color 's constructor takes three int s from 0-255 or three float s from 0-1. 您得到的错误是因为Color的构造函数从0-255接受三个int ,从0-1接受三个float You are passing three double s. 您正在传递三个double s。 That constructor doesn't exist. 该构造函数不存在。

Either way, this is a poor and overcomplicated way to generate a random color. 无论哪种方式,这都是生成随机颜色的较差且过于复杂的方式。 Just do something like this: 只是做这样的事情:

private static final Random generator = new Random();

public static Color randomColor() {
    return new Color(generator.nextInt(256), generator.nextInt(256), generator.nextInt(256));
}

The constructor takes floats, not doubles : 构造函数采用浮点数,而不是double:

public Color(float r,
             float g,
             float b)

颜色在构造函数参数中采用float或int

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

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