Is it possible to have an array or a list of geometric primitives in Java?

Consider drawing an image using a set of the primitive geometric shapes. The solution which I can think of is to combine the items into an array, iterate over it and call the draw method:

Object[] elements = {(new Ellipse2D.Double(200, 200, 40, 40)), 
                     (new Line2D.Double(10, 10, 100, 100)), 
                     (new Rectangle2D.Double(50,50,90,90))};

for (int j=0; j<elements.length; j++){ 
g2d.draw(elements[j]);
}

This should be possible if they all belong to the same parent class. But I was not able to confirm whether such a class exists. Could you please clarify about this object class or maybe there is another way to make an array/list of the shapes?

Edit: Thank you all for the prompt answers! :)

Upvotes: 1

Views: 2567

Answers (2)

Mumrah81
Mumrah81

Reputation: 2054

The draw method of class java.awt.Graphics2D take a java.awt.Shape interface as parameter.

The java.awt.Shape javadoc contains:

All Known Implementing Classes:

Arc2D, Arc2D.Double, Arc2D.Float, Area, BasicTextUI.BasicCaret, CubicCurve2D, CubicCurve2D.Double, CubicCurve2D.Float, DefaultCaret, Ellipse2D, Ellipse2D.Double, Ellipse2D.Float, GeneralPath, Line2D, Line2D.Double, Line2D.Float, Path2D, Path2D.Double, Path2D.Float, Polygon, QuadCurve2D, QuadCurve2D.Double, QuadCurve2D.Float, Rectangle, Rectangle2D, Rectangle2D.Double, Rectangle2D.Float, RectangularShape, RoundRectangle2D, RoundRectangle2D.Double, RoundRectangle2D.Float

So the following perfectly fits your need

java.awt.Shape[] elements = {
        new Ellipse2D.Double(200, 200, 40, 40),
        new Line2D.Double(10, 10, 100, 100), 
        new Rectangle2D.Double(50, 50, 90, 90)};

EDIT: fix in comment added

Upvotes: 3

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

First step is to look at the API docs for one of your types, say, Ellipse2D.Double.

We can see this extends Ellipse2D, and clicking on that gives RectangularShape. That lists (direct) subclasses, but Line2D is not among them. You want the interface Shape and you're done.

Alternatively, look at the Graphics2D.draw method and observe that it declares the parameter as Shape.

You editor/IDE may also be able to give this information more directly.

Upvotes: 3

Related Questions