Add Linear Gradient Color to Shape in JavaFX - Java JavaFX

Java examples for JavaFX:Color

LinearGradient Properties

Property Data TypeDescription
startX double X coordinate of the gradient axis start point
startY double Y coordinate of the gradient axis start point
endX double X coordinate of the gradient axis end point
endY double Y coordinate of the gradient axis end point
proportional boolean Whether the coordinates are proportional to the shape that this gradient fills
cycleMethod opaque CycleMethod boolean Cycle method applied to the gradient Whether this paint is completely opaque
stopsList<Stop> Gradient's color specification

Demo Code

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.scene.shape.Rectangle;
import javafx.stage.Stage;

public class Main extends Application {

  public static void main(String[] args) {
    Application.launch(args);//from  w  w  w . j a  va  2  s.co m
  }

  @Override
  public void start(Stage primaryStage) {
    Group root = new Group();
    Scene scene = new Scene(root, 306, 550, Color.WHITE);

    Rectangle rectangle = new Rectangle();
    rectangle.setX(50);
    rectangle.setY(50);
    rectangle.setWidth(100);
    rectangle.setHeight(70);
    rectangle.setTranslateY(10);

    // Create linear gradient
    LinearGradient linearGrad = new LinearGradient(50,     //startX
                                                   50,     //startY
                                                   50,     //endX
                                                   50 + rectangle.prefHeight(-1) + 25,     //endY
                                                   false,  //proportional
                                                   CycleMethod.NO_CYCLE,
                                                   new Stop(0.1f, Color.rgb(255, 200, 0, .784)),
                                                    new Stop(1.0f, Color.rgb(0, 0, 0, .784)));

    rectangle.setFill(linearGrad);
    root.getChildren().add(rectangle); 


    primaryStage.setScene(scene);
    primaryStage.show();
  }
}

Related Tutorials