gpt4 book ai didi

java - 如何指定要调用类的哪个构造函数?

转载 作者:行者123 更新时间:2023-11-29 03:10:18 25 4
gpt4 key购买 nike

我正在从另一个类创建定义数量的对象,并尝试使用 java.awt.Color 随机化每个对象的颜色。

for (int i = 0; i < numBalls; i++){       
ballsInSim.add(
new BoxBall(
0,
0,
(int) boxWidth,
(int) boxHeight,
rng.nextInt(35) + 15,
rng.nextInt(500) + 25,
rng.nextInt(500) + 25,
Color.BLUE, // Create new Colour here using constructor
myCanvas
)
);
}

当前 Color.BLUE 所在的位置,我想调用 Color 的构造函数之一,该构造函数使用三个整数表示红色、绿色和蓝色值 (Color(int r, int g, int b)).

如何调用该构造函数?我是 Java 的新手,我在解决这个问题时遇到了一些麻烦。

最佳答案

为了达到你想要的效果,只需添加以下内容:

new Color(0, 0, 255)

所以本质上,它看起来像这样:

ballsInSim.add(new BoxBall(0, 0, (int) boxWidth, (int) boxHeight, rng.nextInt(35) + 15, rng.nextInt(500) + 25, rng.nextInt(500) + 25, new Color(0, 0, 255), myCanvas));

为了每次都实现随机颜色:

Random R = new Random(256);
Random G = new Random(256);
Random B = new Random(256);

//your color constructor will then be:
new Color(R.nextInt(), G.nextInt(), B.nextInt());

要了解有关颜色等级的更多信息,请参阅:Color: Java 7

希望对你有帮助

关于java - 如何指定要调用类的哪个构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29734546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com