Search code examples
javaarraylistgeometryshapesgraphics2d

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?


Solution

  • 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.