Graphics2D GradientPaint Applet

GradientPaint fills a shape with colours ranging from a start colour to an end colour in the direction of a line for which you supply the start and end coordinates. The arguments we pass to each GradientPaint constructor are:
  1. the x coordinate of the start colour;
  2. the y coordinate of the start colour;
  3. the start colour;
  4. the x coordinate of the end colour;
  5. the y coordinate of the end colour;
  6. the end colour;
  7. optionally a Boolean value which when true causes a cyclic filling pattern.

In the paint method, we use the method setPaint to set the fill to the appropriate GradientPaint for the next rectangle to be drawn. We demonstrate horizontal, diagonal and vertical gradients. See the full code under this screenshot that it generated.

Gradient painting

Gradient painting

namespace gradient_paint_demo;

interface

uses
  java.util, java.applet.*, java.awt.*;

type
  gradient_paint_demo = public class(Applet)
  private
  var
    width, height : Integer;
    rect11, rect12, rect21, rect22 : Rectangle2D;
    gradient11, gradient12, gradient21, gradient22 : GradientPaint;
    green1, green2 : Color;
  public
    method init(); override;
    method paint(g: Graphics); override;
  end;

implementation

method gradient_paint_demo.init;
begin
  height := getSize.height;
  width := getSize.width;
  rect11 := new Rectangle2D.Float(0, 0, width / 2 - 5, height / 2 - 5);
  gradient11 := new GradientPaint(0, 0, Color.green,  width / 2 - 5, 0, Color.blue);
  rect12 := new Rectangle2D.Float(width / 2 + 5, 0, width / 2 - 5, height / 2 - 5);
  gradient12 := new GradientPaint(width / 2 - 5, 0, Color.green,  3 * width / 4 + 2 , 0, Color.blue, true);

  rect21 := new Rectangle2D.Float(0, height / 2 + 5, width / 2 - 5, height / 2 - 5);
  gradient21 := new GradientPaint(0, height / 2 + 5, Color.red,  width / 2 + 5, height, Color.blue);
  rect22 := new Rectangle2D.Float(width / 2 + 5, height / 2 + 5, width / 2 - 5, height / 2 - 5);
  green1 := new Color(50, 240, 50);
  green2 := new Color(10, 80, 10);
  gradient22 := new GradientPaint(width / 2 + 5, height / 2 + 5, green1, width / 2 + 5, height, green2);
end;

method gradient_paint_demo.paint(g : Graphics);
var
  g2 : Graphics2D;
begin
  g2 := Graphics2D(g);
  g2.setPaint(gradient11);
  g2.fill(rect11);
  g2.setPaint(gradient12);
  g2.fill(rect12);
  g2.setPaint(gradient21);
  g2.fill(rect21);
  g2.setPaint(gradient22);
  g2.fill(rect22);

end;

end.


Programming - a skill for life!

Applets using Graphics2D for transforms, gradient painting and pixel drawing in Oxygene for Java