Lana
Lana

Reputation: 171

Can i add other shapes than ellipse2D rectangle2D to "Shape" in Java?

I have an Arraylist that saves all shapes.

ArrayList<Shape> shapes = new ArrayList<Shape>();

The ArrayList is of type Shape and hence has ellipse, rectangle, line, point. But now I want to draw a triangle and save it into that same ArrayList.

Is it possible to do this? I mean can I add other shapes to that Shape, other than Ellipse2D, Rectangle2D, etc?

EDITED

So this is what i use to draw a rectangle for e.g :

private Rectangle2D.Float drawRectangle(int x1, int y1, int x2, int y2) {
            // Get the top left hand corner for the shape
            // Math.min returns the points closest to 0

            int x = Math.min(x1, x2);
            int y = Math.min(y1, y2);

            // Gets the difference between the coordinates and

            int width = Math.abs(x1 - x2);
            int height = Math.abs(y1 - y2);

            return new Rectangle2D.Float(x, y, width, height);
        }

So to draw my triangle i will have this?

public class triangle implements Shape{

Then i pass the parameters to draw the triangle here?

Upvotes: 0

Views: 415

Answers (2)

camickr
camickr

Reputation: 324108

Check out Playing With Shapes for some interesting ideas.

It shows you how to create a Triangle using the Polygon class:

Polygon triangle = new Polygon();
triangle.addPoint(0, 0);
triangle.addPoint(15, 30);
triangle.addPoint(30, 0);
shapes.add( triangle );

It also shows how to make more complex shapes like stars and hexagons using a utility class provided in the link.

Upvotes: 1

Quanturium
Quanturium

Reputation: 5696

Shape is an interface. Therefore you can add every class implementing this interface to your ArrayList. from the documentation here you can add all of those from the java APIs:

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

If you create a class implementing the interface Shape, you will also be able to add your object to your ArrayList.

Upvotes: 1

Related Questions