Search code examples
javatextjavafxcolorsopacity

Set text to random color & opacity javaFX


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:

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);

Solution

  • You can use Math.random() to generate a Double in the range [0,1), so you need to do:

    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());

    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].

    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.

    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.