Academic Java    Java Tutorial  >  Graphics  >  GradientPaint

GradientPaint Example

Java GradientPaint EXAMPLE output GradientPaint allows you to fill a shape with a linear gradient between two colors.

The first two parameters of the GradientPaint constructor are a start coordinate, and the fourth and fifth parameters an end coordinate. Two color parameters are also provided.

From these a gradient of color is formed. A final parameter tells whether or not the gradient should be cyclic beyond the pairs of coordinates.

GradientPaint can be used in any situation where a Graphics2D graphics context can be obtained, typically from a paint() method.
// GradientPaint Example
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;

class GradientPaintExample extends JApplet {

   @Override public void paint(Graphics g) {
      super.paint(g);
      Graphics2D g2 = (Graphics2D)g;

      Rectangle2D r0=new Rectangle2D.Double(50,50,50,50);
      Rectangle2D r1=new Rectangle2D.Double(200,50,50,50);
      Rectangle2D r2=new Rectangle2D.Double(50,150,200,90);

      Color c0=Color.yellow, c1=Color.blue;

      GradientPaint gp=new GradientPaint(0, 0, c0, 5, 5, c1, true);
      g2.setPaint(gp);
      g2.fill(r0);
      g2.setStroke(new BasicStroke(10));
      g2.draw(r1);

      gp = new GradientPaint(50, 200, c1, 250, 200, c0, false);
      g2.setPaint(gp);
      g2.fill(r2);

   }
}