Java Reference
In-Depth Information
You could define an ellipse with the statements:
Point2D.Double position = new Point2D.Double(10,10);
double width = 200.0;
double height = 100;
Ellipse2D.Double ellipse = new Ellipse2D.Double(
position.x, position.y, // Top-left corner
width, height); // width & height of rectangle
You could define an arc that is a segment of the previous ellipse with the statement:
Arc2D.Double arc = new Arc2D.Double(
position.x, position.y, // Top-left corner
width, height, // width & height of rectangle
0.0, 90.0, // Start and extent angles
Arc2D.OPEN); // Arc is open
This defines the upper-right quarter segment of the whole ellipse as an open arc. The angles are
measured anticlockwise from the horizontal in degrees. As we saw earlier the first angular argument is
where the arc starts, and the second is the angular extent of the arc.
Of course, a circle is just an ellipse where the width and height are the same, so the following statement
defines a circle with a diameter of 150:
double diameter = 150.0;
Ellipse2D.Double circle = new Ellipse2D.Double(
position.x, position.y, // Top-left corner
diameter, diameter); // width & height of rectangle
This presumes the point
position
is defined somewhere. You will often want to define a circle by its
center and radius - adjusting the arguments to the constructor a little does this easily:
Point2D.Double center = new Point2D.Double(200, 200);
double radius = 150;
Ellipse2D.Double newCircle = new Ellipse2D.Double(
center.x-radius, center.y-radius, // Top-left corner
2*radius, 2*radius); // width & height of rectangle
The fields storing the coordinates of the top-left corner of the enclosing rectangle and the width and
height are public members of
Ellipse2D
and
Arc2D
objects. They are
x
,
y
,
width
and
height
respectively. An
Arc2D
object also has public members,
start
and
extent
, that store the angles.
Try It Out - Drawing Arcs and Ellipses
Let's modify the
paint()
method in
SketchView.java
once again to draw some arcs and ellipses.
public void paint(Graphics g) {
// Temporary code
Graphics2D g2D = (Graphics2D)g; // Get a Java 2D device context