java 将文本设置为随机颜色和不透明度 javaFX
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35715283/
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
Set text to random color & opacity javaFX
提问by Sunny Dhillon
I need a javafx program to set text to a random color and opacity I'm not sure on how to do it? here is a sample of my code
我需要一个 javafx 程序来将文本设置为随机颜色和不透明度我不知道该怎么做?这是我的代码示例
Text text1 = new Text();
text1.setText("Java");
text1.setFont(Font.font("Times New Roman", FontWeight.BOLD, FontPosture.ITALIC, 22));
text1.setRotate(90);
gridpane.add(text1, 3, 1);
回答by CAD97
You can use Math.random()
to generate a Double
in the range [0,1)
, so you need to do:
您可以使用在 range 中Math.random()
生成一个,因此您需要执行以下操作:Double
[0,1)
text.
setOpacity
(Math.random());
text.
setOpacity
(Math.random());
Color took a little more digging through the docs, but can be accomplished with:
颜色需要更多地挖掘文档,但可以通过以下方式完成:
text.
setFill
(
Color.color
(Math.random(), Math.random(), Math.random());
text.
setFill
(
Color.color
(Math.random(), Math.random(), Math.random());
setFill
comes from Shape
, which Text
inherits from. setFill
takes a Paint
, which Color
is the simplest implementation of. Color.color(double, double, double)
takes the rgb value with doubles in the range [0,1].
setFill
来自Shape
,它Text
继承自。setFill
需要一个Paint
,这Color
是最简单的实现。Color.color(double, double, double)
使用范围 [0,1] 中的双精度 rgb 值。
Learn how to navigate through the docs and you'll be able to find these sorts of things on your own quickly in the future!
了解如何浏览文档,将来您将能够自己快速找到这些类型的东西!
Note: opacity/rgb color all take doubles of the range [0,1] where Math.random()
produces in the range [0,1). If you're unfamiliar with this notation, this means Math.random()
will NEVER produce 1, only a number smaller than 1 by possible accuracy. This means that you will never have a 100% fully opaque/r/g/b with this method but in reality you probably can't tell the difference, so it's better to use the less complicated method.
注意:不透明度/RGB 颜色都采用范围 [0,1] 的两倍,其中Math.random()
产生范围 [0,1)。如果你不熟悉这个符号,这意味着Math.random()
永远不会产生 1,只有一个小于 1 的数字可能的准确性。这意味着用这种方法你永远不会有 100% 完全不透明的/r/g/b,但实际上你可能无法区分差异,所以最好使用不太复杂的方法。
Note 2: javafx.scene.paint.Color#color
actually provides a four-argument constructor that includes opacity, but I would recommend setting the opacity of the Text node itself as above rather than the opacity of the Paint.
注 2:javafx.scene.paint.Color#color
实际上提供了一个包含不透明度的四参数构造函数,但我建议将 Text 节点本身的不透明度设置为上述,而不是 Paint 的不透明度。