我正在尝试为自定义Shape类编写一个包含方法,但是如果可能的话,我宁愿简单编写自己的方法而不实现Shape类。如何编写一个包含自定义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传递 – motifesta
您可以发布扩展'Shape'的各种形状类的代码吗?你有没有实施过这样的课程? –