Getting in Shape

By David Wall, ITworld |  News

The Java2D classes, as defined in the java.awt.geom package, define
four basic geometric constructions (plus the point, but that hardly
counts). The constructions are the line, the ellipse, the rectangle,
and the generalized path.

Perfect circles are a subset of the ellipse class and regular squares,
a special kind of rectangle. The generalized path (defined in the
GeneralPath class) can define any series of joined line segments, or an
irregular closed space.

This exercise involves two classes. The first, LineDrawings, defines an
array of seven Shape objects. In the array, there are one square, one
circle, one triangle (defined as a GeneralPath), and four line segments
that together for a sort of star shape.

import java.awt.*;
import java.awt.geom.*;
class LineDrawings {
static Shape shapeArray[];
static {
shapeArray = new Shape[7];
shapeArray[0] = new Rectangle2D.Float(50f,50f,200f,200f);
shapeArray[1] = new Ellipse2D.Float(50f,300f,200f,200f);
GeneralPath triangle = new GeneralPath();
triangle.moveTo(300f,50f);
triangle.lineTo(300f,250f);
triangle.lineTo(500f,250f);
triangle.closePath();
shapeArray[2] = (Shape)triangle;
shapeArray[3] = new Line2D.Float(300f,400f,500f,400f);
shapeArray[4] = new Line2D.Float(300f,300f,500f,500f);
shapeArray[5] = new Line2D.Float(400f,300f,400f,500f);
shapeArray[6] = new Line2D.Float(500f,300f,300f,500f);
}
static public Shape[] getShapeArray() {
return(shapeArray);
}
}

The second class renders those shapes. It relies on the DefaultStroke
class as a vehicle for rendering the shapes visually, taking them out
of the realm of abstraction.

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
class DefaultStroke extends Frame {
Shape shapeArray[];
public static void main(String arg[]) {
new DefaultStroke();
}
DefaultStroke() {
super("DefaultStroke");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{ System.exit(0); } } );
setSize(550,550);
shapeArray = LineDrawings.getShapeArray();
show();
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
for(int i=0; i g2.draw(shapeArray[i]);
}
}

Thanks to Arthur Griffith for these code samples.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Answers - Powered by ITworld

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Ask a Question
randomness