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.GREEN.

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.geom;

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

public class GradientPaintDemo extends JComponent {
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;

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

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

    public static void main(String[] args) {
        JFrame frame = new JFrame("Gradient Paint Demo");
        frame.getContentPane().add(new GradientPaintDemo());
        frame.setSize(new Dimension(420, 350));

This code snippet produce the following output:

Gradient Paint Demo

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you đŸ¥³

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.