Java Reference
In-Depth Information
g2D.draw(line);
p1.setLocation(p1.x + width1, p1.y);
p2.setLocation(p2.x + width2, p2.y);
g2D.draw(new Line2D.Float(p1,p2));
p1.setLocation(p1.x, p1.y + height1);
p2.setLocation(p2.x, p2.y + height2);
g2D.draw(new Line2D.Float(p1,p2));
p1.setLocation(p1.x - width1, p1.y);
p2.setLocation(p2.x - width2, p2.y);
g2D.draw(new Line2D.Float(p1, p2));
p1.setLocation(p1.x, p1.y - height1);
p2.setLocation(p2.x, p2.y - height2);
g2D.draw(new Line2D.Float(p1, p2));
g2D.drawString("Lines and rectangles", 60, 250); // Draw some text
}
If you type this in correctly and recompile
SketchView
class, the Sketcher window will look like:
How It Works
After casting the graphics context object that is passed to the
paint()
method to type
Graphics2D
we set the drawing color to red. All subsequent drawing that we do will be in red until we change the
color with another call to
setPaint()
. We define a
Point2D.Floa
t object to represent the position
of the first rectangle, and we define variables to hold the width and height of the rectangle. We use
these to create the rectangle by passing them as arguments to the constructor that we have seen before,
and display the rectangle by passing the
rect
object to the
draw()
method for the graphics context,
g2D
. The second rectangle is defined by essentially the same process, except that this time we create the
Rectangle2D.Float
object in the argument expression for the
draw()
method.