creating a rectangle from 2 specific points
Asked Answered
F

2

7

I am trying to create a rectangle in Java but only with awt package classes.

I can only click two points and the program must calculate the width and height and draw a rectangle between those exact two points.

The following doesn't work for me:

package ie.iact.shapes;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;

public class Rect extends Shapes {``

    private Point secondPoint;

    public Rect(Point f, Point s) {
        setFirstPoint(f);
        setSecondPoint(s);

    }

    @Override
    public void draw(Graphics g) {
        int x1 = firstPoint.x;
        int y1 = firstPoint.y;
        int x2 = secondPoint.x;
        int y2 = secondPoint.y;
        int a;
        int b;
        if (x1 < x2) {
            a = x1;
        } else {
            a = x2;
        }
        if (y1 < y2) {
            b = y1;
        } else {
            b = y2;
        }
        int width = secondPoint.x - a;
        int hight = secondPoint.y - b;
        g.drawRect(getFirstPoint().x, getFirstPoint().y, secondPoint.x, secondPoint.y);

    }

    public Point getSecondPoint() {
        return secondPoint;
    }

    public void setSecondPoint(Point secondPoint) {
        this.secondPoint = secondPoint;
    }
}
Fellow answered 15/5, 2013 at 11:8 Comment(3)
Take a look at the g.drawRect call. You go to all the trouble of calculating the top/left corner and the height and width, but ten ignore tis values completely...Maremma
For better help sooner, post an SSCCE.Phlegethon
thank u all but the code was perfect. I was overriding it in another classFellow
M
9

Rectangle class can already handle all of your calculations:

Rectangle rect= new Rectangle(point1);
rect.add(point2);

g.fillRect(rect.x, rect.y, rect.width, rect.height);
Mintun answered 25/10, 2013 at 1:35 Comment(0)
D
0

Alternatively you can use setFrameFromDiagonal:

Rectangle rect= new Rectangle();
rect.setFrameFromDiagonal(point1, point2);

g.fillRect(rect.x, rect.y, rect.width, rect.height);
Dib answered 14/9, 2015 at 9:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.