Credits

Thursday, March 24, 2011

Java's Graphics Methods on Geometry

In a previous post on Graphics,  the class can also draw  geometric shapes like circles, rectangles, oval, squares, arcs and polygons to complement any other methods of Java.


The draw and fill methods can be used to draw an outline and solid shapes respectively. Thus, with the parameters required in methods, we can actually draw the shapes  with specified size and position.


The program below allows the drawing of different shapes. To draw a polygon, we have to get the coordinates of points connecting the lines and use drawPolygon or fillPolygon methods to draw the shape.


int xPoints[]={42,52,72,52,60,40,15,28,9,32,42};
int yPoints[]={38,62,68,80,105,85,102,75,58,60,38};
:
:
g.drawPolygon(xPoints,yPoints,xPoints.length); //to fill a solid polygon 

[+/-] show/hide

import java.applet.*;
import java.awt.*;

public class GraphicsRectsCircles extends Applet {
int xPoints[]={42,52,72,52,60,40,15,28,9,32,42};
int yPoints[]={38,62,68,80,105,85,102,75,58,60,38};
int size=xPoints.length;
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.drawLine(5,5,50,5);
g.drawLine(5,50,50,50);
g.drawLine(5,5,5,50);
g.drawLine(50,5,50,50);


g.fill3DRect(100,50,80,80,true);
g.setColor(Color.black);
g.drawRoundRect(20,20,80,80,0,0);
g.drawRoundRect(120,20,80,80,10,10);
g.drawRoundRect(220,20,80,80,40,40);
g.drawRoundRect(280,150,20,50,20,50);//oblong
g.fillRoundRect(320,20,80,80,80,80);

g.setColor(Color.blue);
setBackground(Color.pink);
g.fillRect(20, 160, 80, 80);
g.clearRect(40, 180, 50, 50);


g.fillArc(120, 160, 100, 100, 20, 320);
g.fillArc(200, 160, 100, 100, 340, 40);
g.fillArc(400, 160, 100, 100, 90, 270);
g.setColor(Color.yellow);
//g.drawPolygon(xPoints,yPoints,xPoints.length); //to draw a polygon outline
g.drawPolygon(xPoints,yPoints,xPoints.length); //to fill a solid polygon
// or through the lines below, produces same result
//Polygon myPolygon=new Polygon(xPoints,yPoints,size);
//g.fillPolygon(myPolygon);
}
}

AddThis