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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:30:05  来源:igfitidea点击:

Set text to random color & opacity javaFX

javatextjavafxcolorsopacity

提问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 Doublein 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());

setFillcomes from Shape, which Textinherits from. setFilltakes a Paint, which Coloris 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#coloractually 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 的不透明度。