How to apply radial gradient (color) to a node in JavaFX?



You can apply colors to shapes in JavaFX using the setFill() method it adds color to the interior of the geometrical shapes or background.

This method accepts an object of the javafx.scene.paint.Paint class as a parameter. It is the base class for the color and gradients that are used to fill the shapes and backgrounds with color.

The javafx.scene.paint.RadialGradient class in JavaFX is a subclass of the Paint and using this you can fill a shape with a circular color gradient pattern.

To apply a radial gradient pattern to a geometrical shape −

  • Instantiate the RadialGradient class by passing the required parameters.

  • Set the created gradient to the shape using the setFill() method.

Example

import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.paint.CycleMethod; import javafx.scene.paint.RadialGradient; import javafx.scene.paint.Stop; import javafx.stage.Stage; import javafx.scene.shape.Circle; import javafx.scene.shape.Ellipse; import javafx.scene.shape.Polygon; import javafx.scene.shape.Rectangle; public class RadialGradientExample extends Application {    public void start(Stage stage) {       //Drawing a circle       Circle circle = new Circle(75.0f, 65.0f, 40.0f );       //Drawing a Rectangle       Rectangle rect = new Rectangle(150, 30, 100, 65);       //Drawing an ellipse       Ellipse ellipse = new Ellipse(330, 60, 60, 35);       //Drawing Polygon       Polygon poly = new Polygon(410, 60, 430, 30, 470, 30, 490, 60, 470, 100, 430, 100 );       //Setting the radial gradient       Stop[] stops = new Stop[] {          new Stop(0.0, Color.WHITE),          new Stop(0.3, Color.RED),          new Stop(1.0, Color.DARKRED)       };       RadialGradient gradient = new RadialGradient(0, 0, 300, 178, 60, false, CycleMethod.NO_CYCLE, stops);       //Setting the pattern       circle.setFill(gradient);       circle.setStrokeWidth(3);       circle.setStroke(Color.CADETBLUE);       rect.setFill(gradient);       rect.setStrokeWidth(3);       rect.setStroke(Color.CADETBLUE);       ellipse.setFill(gradient);       ellipse.setStrokeWidth(3);       ellipse.setStroke(Color.CADETBLUE);       poly.setFill(gradient);       poly.setStrokeWidth(3);       poly.setStroke(Color.CADETBLUE);       //Setting the stage       Group root = new Group(circle, ellipse, rect, poly);       Scene scene = new Scene(root, 600, 150);       stage.setTitle("Radial Gradient");       stage.setScene(scene);       stage.show();    }    public static void main(String args[]){       launch(args);    } }

Output

Updated on: 2020-05-16T06:57:03+05:30

616 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements