About Special Effects in JavaFX - dummies

About Special Effects in JavaFX

By Doug Lowe

Special Effects in JavaFX can allow you to do things like embellish the appearance of the nodes in your scene graph by adding special effects such as blurs, shadows, color displacements, glows, and so on. You can even add perspective to give your application a three-dimensional look without having to do actual 3D programming.

Special effects in JavaFX derive from the Effect class, an abstract class that has a wide variety of subclasses you can use to create a special effect. There are a total of 17 subclasses of the Effect class, but you might not need to learn all 17. Instead, start by focusing on those effects that let you make your shapes look more realistic by adding blurriness, shadows, reflections, and glow.

All the effects work in a similar way. First, you create an instance of the effect’s class by calling its default constructor. Then, you optionally set the properties of the effect by calling one or more set methods. (In many cases, the default property values are appropriate, so you can often skip this step.) Finally, you apply the effect to a node by calling the node’s setEffect method.

For example, here’s a bit of code that creates a rectangle, fills it, and then adds a drop shadow:

Rectangle r1 = new Rectangle(50, 50, 100, 100);
DropShadow shadow1 = new DropShadow();

This figure shows the outcome of this effect. As you can see, the rectangle is surrounded by a subtle shadow.


The setEffect method is defined by the Node class, which means that you can apply an effect to any node in your scene graph. The effect is applied not only to the node whose setEffect method you call, but also to any children of that node. In fact, if you call setEffect on a scene’s root node, the effect will be applied to the entire scene.