【问题标题】:creating a rectangle from 2 specific points从 2 个特定点创建一个矩形
【发布时间】:2013-05-09 22:19:12
【问题描述】:

我正在尝试在 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;
    }
}

【问题讨论】:

  • 看看 g.drawRect 调用。你去计算左上角和高度和宽度的所有麻烦,但十个完全忽略 tis 值......
  • 如需尽快获得更好的帮助,请发帖SSCCE
  • 谢谢大家,但代码很完美。我在另一个类中覆盖它

标签: java awt java-2d shapes


【解决方案1】:

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

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

g.fillRect(rect.x, rect.y, rect.width, rect.height);

【讨论】:

    【解决方案2】:

    您也可以使用setFrameFromDiagonal:

    Rectangle rect= new Rectangle();
    rect.setFrameFromDiagonal(point1, point2);
    
    g.fillRect(rect.x, rect.y, rect.width, rect.height);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      • 2013-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多