Saturday, July 12, 2008

Creating 2D Shapes in Java

The Java2D API provides advanced two-dimensional graphics capabilities for programmers who require detailed and complex graphical manipulations. it includes features for processing line art, text and images in packages java.awt, java.awt.image, java.awt.color, java.awt.font, java.awt.geom, java.awt.print and java.awt.image.renderable.

The code shown below constructs a ring of five pointed stars constructed from straight lines and complex curves.

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

import javax.swing.JFrame;

public class shapes extends JFrame{

//set window's title bar string, background color and dimensions
public shapes(){

super("Drawing 2D shapes");

getContentPane().setBackground(Color.WHITE);
setSize(400,400);
setVisible(true);
}

//draw general paths
public void paint(Graphics g){
super.paint(g);
int xPoints[]={55,67,109,73,83,55,27,37,1,43};
int yPoints[]={0,36,36,54,96,72,96,54,36,36};

Graphics2D g2d = (Graphics2D)g;

//create a star from a series of points
GeneralPath star = new GeneralPath();

//set the initials coordinates of the General Path
star.moveTo(xPoints[0],yPoints[0]);

//create the star
for(int count =1; count<xPoints.length; count++)
star.lineTo(xPoints[count],yPoints[count]);

//close the shape
star.closePath();

//translate the origin to (200,200)
g2d.translate(200,200);

//rotate around origin and draw stars in random colors
for(int count =1; count<=20; count++){


//rotate coordinate system
g2d.rotate(Math.PI/10.0);

//set random drawing color
g2d.setColor(new Color(
(int)(Math.random()*256),
(int)(Math.random()*256),
(int)(Math.random()*256)));

//draw filled star
g2d.fill(star);
}
}

public static void main(String args[]){

shapes application = new shapes();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

}

Run the program and view the result!!!

1 comment:

varun said...

Fine Saatvi keep it up