【发布时间】:2015-07-20 01:15:17
【问题描述】:
我正在尝试为自定义 Shape 类编写 contains 方法,但如果可能的话,我更愿意在不实现 Shape 类的情况下简单地编写自己的方法。
但是,我该如何编写这样一个方法来测试指定的 X 和 Y 坐标是在我的形状内还是在边框上?
[编辑]
这是一个示例类
abstract class BoundedShape extends Shape {
protected Point upperLeft;
protected int width, height;
public BoundedShape(Color color, Point corner, int wide, int high) {
strokeColor = color;
upperLeft = corner;
width = wide;
height = high;
}
public void setShape(Point firstPt, Point currentPt) {
if (firstPt.x <= currentPt.x)
if (firstPt.y <= currentPt.y)
upperLeft = firstPt;
else
upperLeft = new Point(firstPt.x, currentPt.y);
else if (firstPt.y <= currentPt.y)
upperLeft = new Point(currentPt.x, firstPt.y);
else
upperLeft = currentPt;
width = Math.abs(currentPt.x - firstPt.x);
height = Math.abs(currentPt.y - firstPt.y);
}
}
另一个
public class Line extends Shape {
protected Point firstPoint;
protected Point secondPoint;
public Line(Color color, Point p1, Point p2) {
strokeColor = color;
firstPoint = p1;
secondPoint = p2;
}
public void setEndPoint(Point endPoint) {
secondPoint = endPoint;
}
public void draw(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(strokeColor);
g2d.drawLine(firstPoint.x, firstPoint.y, secondPoint.x,
secondPoint.y);
}
另一个
public class Rect extends BoundedShape {
public Rect(Color color, Point corner, int wide, int high) {
super(color, corner, wide, high);
}
public void draw(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(strokeColor);
g2d.drawRect(upperLeft.x, upperLeft.y, width, height);
}
}
【问题讨论】:
-
Shape类的结构是什么? -
基础抽象类非常简单,仅具有抽象的 draw() 方法。它由自定义形状实现,通过点、高度/宽度或 x/y
-
你能贴出扩展
Shape的各种形状类的代码吗?你实现过这样的类吗? -
您可以在
Shape中声明 contains 方法,该方法需要被所有类覆盖。 -
对,但我没有实现 java Shape 类...我正在努力确定如何编写自己的 contains 方法
标签: java equals contains shape