In this tutorials, we are going to see how to use the Java Graphics2D class.

Java Graphics class is a abstract base class, it allows the application to draw something on different AWT or Swing components.

Java Graphics2D Class :

The Graphics2D Class is extended class of Graphics class, it provides more sophisticated controls over text layout, color management and coordinate transformations.

Java Graphics2D Example:

Since this example on Java Graphics2D, I am going to present an interesting output here.

Graphics2D_Demo.java
package com.onlinetutorialspoint.swing;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Graphics2D_Demo extends JPanel{

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        
        int[] xValues = {55,67,109,73,83,55,27,37,1,43};
        int[] yValues = {0,36,36,54,96,72,96,54,36,36};
        
        Graphics2D graphics2D  = (Graphics2D) g;
        GeneralPath path = new GeneralPath();
        
        path.moveTo(xValues[0], yValues[0]);
        
        for (int i= 1;i<xValues.length;i++){
            path.lineTo(xValues[i], yValues[i]);
        }
        
        path.closePath();
        graphics2D.translate(150, 150);
        Random rNumbers = new Random();
        for (int i= 1;i<=20;i++){
            graphics2D.rotate(Math.PI/10.0);
            graphics2D.setColor(new Color(rNumbers.nextInt(256),rNumbers.nextInt(256),rNumbers.nextInt(256)));
            graphics2D.fill(path);
        }
        
    }
    public static void main(String[] args) {
        JFrame frame = new JFrame("Graphics2D Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        Graphics2D_Demo demo = new Graphics2D_Demo();
        frame.add(demo);
        frame.setBackground(Color.WHITE);
        frame.setSize(315, 330);
        frame.setVisible(true);
    }

}

Output :

Java Graphics2D Class Example

Happy Learning 🙂