这是一个家庭作业问题。我有一段时间试图使用getX()和getY()来创建xPoints和yPoints,请帮忙。
package shapes;
import java.awt.Color;
import java.awt.Graphics;
public class Triangle extends Rectangle {
//private int[] xPoints = {50, 100, 150};
//private int[] yPoints = {200, 100, 200};
private int[] xPoints = {(getX()/2), getX(), (getX()+(getX()/2))};
private int[] yPoints = {(getY()+getY()), getY(),(getY()+getY())};
public Triangle(int x, int y, int w, int h, Color lineColor, Color fillColor, boolean fill) {
super(x, y, w, h, lineColor, fillColor, fill);
}
public void draw(Graphics g) {
// Be nice. Save the state of the object before changing it.
Color oldColor = g.getColor();
if (isFill()) {
g.setColor(getFillColor());
g.fillPolygon(xPoints, yPoints, 3);
}
g.setColor(getLineColor());
g.drawPolygon(xPoints, yPoints, 3);
//g.drawOval(getX(), getY(), getWidth(), getHeight());
// Set the state back when done.
g.setColor(oldColor);
}
public int getArea() {
//return area;
return getWidth()*getHeight();
}
/**
* Returns a String representing this object.
*/
public String toString() {
//return "Triangle: \n\tx = " + getX() + "\n\ty = " + getY() +
//"\n\tw = " + getWidth() + "\n\th = " + getHeight();
return "Triangle";
}
}
//这里是SHAPE.JAVA文件......
package shapes;
import java.awt.Color;
import java.awt.Graphics;
public abstract class Shape {
private int x, y;//,w,h;
private Color lineColor;
public Shape(int x, int y, Color lineColor) {
this.x = x;
this.y = y;
this.lineColor = lineColor;
}
public abstract void draw(Graphics g);
public abstract boolean containsLocation(int x, int y);
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Color getLineColor() {
return lineColor;
}
public void setLineColor(Color lineColor) {
this.lineColor = lineColor;
}
}
答案 0 :(得分:1)
首先,让我们考虑一下你在开场白线上想要做些什么。
public class Triangle extends Rectangle {
最后我查了一下,Triangle不是一种Rectangle。也许您应该将其修改为类似
的内容public class Triangle extends Shape {
或者更合适的东西。查看形状类以找到确切的一个。
现在,让我们考虑一下你在课堂上做了什么。
private int[] xPoints = {(getX()/2), getX(), (getX()+(getX()/2))};
private int[] yPoints = {(getY()+getY()), getY(),(getY()+getY())};
您确定需要在此定义吗?我敢打赌,Shape
类已经有xPoints和yPoints的数组。在那里寻找灵感。
此外,如果Shape具有xPoints和yPoints,并且他们正在尝试使用它们,那么它们将无法实现!由于您要定义Triangle.xPoints
,Shape.xPoints
会被“遮蔽”...意味着Shape
中的xPoints将指向它自己的xPoints
,而不是您定义的那个,结果在一个非常快的NullPointerException。
现在,使用Rectangle,很容易将其定义为X,Y + W,H。它看起来像这样:
X,Y X+W,Y
+---------+
| |
| |
+---------+
X,Y+H X+W,Y+H
现在你怎么代表你的三角形呢?看起来你需要考虑如何代表你的三角形。也许Shape类中的一些信息也可以帮助你。