Monday , December 11 2017
Home / java / Java Graphics2D Class Example

Java Graphics2D Class Example

In this tutorials, we are going to see how to use 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.


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 🙂

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Recommended

Java JColorChooser Example

In this example I am going to show you how to use apply different colors …

Leave a Reply

Your email address will not be published. Required fields are marked *