Java Reference
In-Depth Information
You can define a line by supplying two
Point2D
objects to a constructor, or two pairs of (
x,y
) coordinates.
For example, here's how you define a line by two coordinate pairs:
Line2D.float line = new Line2D.Float(5.0f, 100.0f, 50.0f, 150.0f);
This draws a line from the point (5.0, 100.0) to the point (50.0, 150.0). You could also create the same
line using
Point2D.Float
objects, like this:
Point2D.Float p1 = new Point2D.Float(5.0f, 100.0f);
Point2D.Float p2 = new Point2D.Float(50.0f, 150.0f);
Line2D.float line = new Line2D.Float(p1, p2);
You draw a line on a component using the
draw()
method for a
Graphics2D
object. For example:
g2D.draw(line); // Draw the line
To create a rectangle, you specify the coordinates of its top-left corner, and the width and height of the
rectangle:
float width = 120.0f;
float height = 90.0f;
Rectangle2D.Float rectangle = new Rectangle2D.Float(50.0f, 150.0f, width, height);
The default constructor creates a rectangle at the origin with a zero width and height. You can set the
position, width, and height of a rectangle by calling its
setRect()
method. There are three versions of this
method. One of them accepts arguments for the coordinates of the top-left corner and the width and height
as values of type
float
, exactly as in the constructor. Another accepts arguments with the same meaning but
of type
double
. The third
setRect()
method accepts an argument of type
Rectangle2D,
so you can pass
any type of rectangle object to it.