6

我正在尝试在 Java 中创建一个矩形,但仅使用awt 包类。

我只能单击两个点,程序必须计算宽度和高度,并在这两个点之间绘制一个矩形。

以下对我不起作用:

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;
    }
}
4

2 回答 2

10

Rectangle类已经可以处理您的所有计算:

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

g.fillRect(rect.x, rect.y, rect.width, rect.height);
于 2013-10-25T01:35:35.477 回答
-1

或者,您可以使用setFrameFromDiagonal

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

g.fillRect(rect.x, rect.y, rect.width, rect.height);
于 2015-09-14T09:29:08.650 回答