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

JavaFXObject Oriented ProgrammingProgramming

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.LinearGradient class in JavaFX is a subclass of the Paint and using this you can fill a shape with a circular linear-gradient pattern.

To apply a radial gradient pattern to a geometrical shape −

  • Instantiate the LinearGradient 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.LinearGradient;
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 LinearGradientExample 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 linear gradient
      Stop[] stops = new Stop[] {
         new Stop(0, Color.DARKSLATEBLUE),
         new Stop(1, Color.DARKRED)
      };
      LinearGradient gradient =
      new LinearGradient(0, 0, 1, 0, true, 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("Linear Gradient");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

raja
Published on 16-May-2020 06:54:28
Advertisements