我正在嘗試爲自定義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'的各種形狀類的代碼嗎?你有沒有實施過這樣的課程? –