JavaFX: How to Combine Effects

By Doug Lowe

JavaFX special effects can have a major impact on the appearance of your scenes. But wait, there’s more! JavaFX lets you improve the appearance of your scenes even more by allowing you to combine special effects, essentially laying one effect atop another.

To combine effects, you use the setInput method, which is available for all the main effects classes. Simply put, you create an instance of an effect class, create an instance of a second effects class, and chain the first to the second by calling the first effect’s setInput method and specifying the second effect as the input.

For example, suppose you want to combine a reflection with a shadow and then apply the combined effect to a rectangle. You can do so like this:

Rectangle rect = new Rectangle(100,100);
DropShadow shadow = new DropShadow();
Reflection reflect = new Reflection();
reflect.setInput(shadow);
rect.setEffect(reflect);

In this example, the shadow effect will first be rendered on the rectangle. Then, the reflection effect will be rendered on the rectangle, creating a reflection of both the rectangle and its shadow.

image0.jpg

This figure shows how the chessboard that was created in the preceding section appears with a drop shadow chained to the perspective transform. The code that creates the perspective and shadow effects is as follows:

PerspectiveTransform e = new PerspectiveTransform();
e.setUlx(100);    // Upper left
e.setUly(100);
e.setUrx(450);    // Upper right
e.setUry(100);
e.setLlx(0);      // Lower left
e.setLly(300);
e.setLrx(400);    // Lower right
e.setLry(300);
DropShadow shadow = new DropShadow();
shadow.setWidth(20);
shadow.setHeight(20);
shadow.setOffsetX(20);
shadow.setOffsetY(20);
shadow.setRadius(30);
e.setInput(shadow);board.setEffect(e);
board.setEffect(e);

As you can see, the perspective transform is applied to the chessboard and its shadow, creating a realistic effect of the chessboard floating above a surface.