Creating Visual Effects in JavaFX

Previous

9 Creating a Chain of Effects

Some of the effects have an input property that you can use to create a chain of effects. The chain of effects can be a tree-like structure, because some effects have two inputs and some do not have any.

In Figure 9-1 the reflection effect is used as an input for the drop shadow effect, which means that first the rectangle is reflected by the reflection effect and then the drop shadow effect is applied to the result.

Figure 9-1 Shadow and Reflection

Description of Figure 9-1 follows
Description of "Figure 9-1 Shadow and Reflection"

Example 9-1 Rectangle with a Shadow and Reflection Sequentially Applied

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.*;
import javafx.stage.*;
import javafx.scene.shape.*;
import javafx.scene.effect.*;
import javafx.scene.paint.*;
import javafx.scene.text.*;
 
public class HelloEffects extends Application {
 
    Stage stage;
    Scene scene;

    @Override public void start(Stage stage) {
        stage.show();
 
        scene = new Scene(new Group());
        ObservableList<Node> content = ((Group)scene.getRoot()).getChildren();
 
        content.add(chainEffects());
        stage.setScene(scene);
    }
    static Node chainEffects() {
        
        Rectangle rect = new Rectangle();
        rect.setFill(Color.RED);
        rect.setWidth(200);
        rect.setHeight(100);
        rect.setX(20.0f);
        rect.setY(20.0f);
 
        DropShadow ds = new DropShadow();
        ds.setOffsetY(5.0);
        ds.setOffsetX(5.0);
        ds.setColor(Color.GRAY);
        
        
        Reflection reflection = new Reflection();
 
        ds.setInput(reflection);    
        rect.setEffect(ds);
 
        return rect;
    }
    public static void main(String[] args) {
        Application.launch(args);
    }
}

Note:

If you change the last two lines in the static Node chainEffects() to reflection.setInput(ds); and rect.setEffect(reflection);, first the drop shadow will be applied to the rectangle, and then the result will be reflected by the reflection effect.


For more information about particular classes, methods, or additional features, see the API documentation.

Previous