How to Draw Transparently in JavaFX

By Doug Lowe

JavaFX lets you create partially transparent colors by setting an opacity value for the color. An opacity value of 1.0 indicates that the color is completely opaque, whereas a value of 0.0 means the color is completely transparent. To create a partially transparent color, you set the opacity value somewhere between 0.0 and 1.0.

There are several ways to do that, but the easiest is to use one of the several static methods of the Color class that create a color from its constituent parts. Here, rgb method is used, which accepts four parameters: three integers representing the red, green, and blue components of the color (values can be 0 to 255), and a double that represents the opacity.

For example, to create a 50% transparent black, you’d use the rgb method, like this:

Color.rgb(0, 0, 0, 0.5);

To create a 20% transparent red, use this:

Color.rgb(255, 0, 0, 0.2);

The figure shows a scene with three rectangles, two of which have transparency applied. The following snippet shows the code used to create these three rectangles:

Rectangle r1 = new Rectangle(0,75,350,40);
r1.setFill(Color.rgb(200, 200, 200, 1.0));
Rectangle r2 = new Rectangle(50,5,100,200);
r2.setFill(Color.rgb(200, 200, 200, 0.5));
Rectangle r3 = new Rectangle(200,5,100,200);
r3.setFill(Color.rgb(200, 200, 200, 0.5));

As you can see, all three of these rectangles specify a shade of gray by using the values 200, 200, and 200 for the red, green, and blue color components. The first rectangle specifies 1.0 for the opacity; the other two specify 0.5 for the opacity. As a result, you can see the first rectangle behind the other two rectangles.