How do I create a gradient paint in Java 2D?

To change the color of a graphics shape we can use the setPaint() method. For a simple coloring we can pass the color object into this method, such as Color.RED or Color.GREE.

If you want to paint with a gradient paint you can use the GradientPaint class. This class provides a way to fill a shape with a linear color gradient pattern. To create a gradient color pattern you can pass the following parameter to the object constructor.

  • x1: x coordinate of the first specified point in user space
  • y1: y coordinate of the first specified point in user space
  • color1: color at the first specified point
  • x2: x coordinate of the second specified point in user space
  • y2: y coordinate of the second specified point in user space
  • color2: color at the second specified point

package org.kodejava.example.awt.geom;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;

public class GradientPaintDemo extends JApplet {
    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;

        GradientPaint blackToGray = new GradientPaint(50, 50, Color.BLACK,
                300, 100, Color.LIGHT_GRAY);
        g2.setPaint(blackToGray);
        g2.fill(new Rectangle2D.Double(50, 50, 300, 100));

        GradientPaint blueToBlack = new GradientPaint(0, 0, Color.BLUE,
                400, 400, Color.BLACK);
        g2.setPaint(blueToBlack);
        g2.fill(new Rectangle2D.Double(50, 160, 300, 100));
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Gradient Paint Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JApplet applet = new GradientPaintDemo();
        frame.getContentPane().add(applet);
        frame.pack();
        frame.setSize(new Dimension(400, 350));
        frame.setVisible(true);
    }
}

This code snippet produce the following output:

Gradient Paint Demo

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply