编写一个公共实例方法move(),该方法带有两个整数参数,它们表示更改实例变量xPos和yPos的值的数量。该方法应不返回任何值。它应该利用提供的方法delay()暂停,以便可以看到重复运行该方法的效果,例如this.delay(20);
暂停执行20毫秒。
通过移动StickFigure的实例并检查其是否对齐来测试代码。
我的代码在下面,但我似乎无法弄清楚如何将所有3个形状一起移动,只有三角形似乎在移动。
public class StickFigure
{
/*Instance variables*/
private int xPos;//The horizontal position of a StickFigure
private int yPos;//The vertical position of a StickFigure
private Circle head;
private Triangle body;
private Rectangle leg;
public StickFigure()
{
super();
this.head = new Circle (30, OUColour.PINK);
this.body = new Triangle (50, 50, OUColour.RED);
this.leg = new Rectangle (6, 50, OUColour.PINK);
this.setXPos(25);
this.setYPos(220);
this.alignAll();
}
public void setXPos(int newPos)
{
this.xPos = newPos;
this.body.setXPos(newPos);
this.alignAll();
}
public int getXPos()
{
return this.xPos;
}
public void setYPos(int newPos)
{
this.yPos = newPos;
this.body.setYPos(newPos);
this.alignAll();
}
public int getYPos()
{
return this.yPos;
}
public Circle getHead()
{
return this.head;
}
public Triangle getBody()
{
return this.body;
}
public Rectangle getLeg()
{
return this.leg;
}
public void alignHead()
{
this.head.setXPos(this.body.getXPos() + (this.body.getWidth() - this.head.getDiameter())/2);
this.head.setYPos(this.body.getYPos() - this.head.getDiameter());
}
public void alignBody()
{
this.body.setXPos(25);
this.body.setYPos(220);
}
public void alignLeg()
{
this.leg.setXPos(this.body.getXPos() + (this.body.getWidth() - this.leg.getWidth())/2);
this.leg.setYPos(this.body.getYPos() + this.leg.getHeight());
}
public void alignAll()
{
this.alignBody();
this.alignHead();
this.alignLeg();
}
public void move(int xPos, int yPos)
{
this.body.setXPos(xPos + xPos);
this.body.setYPos(yPos + yPos);
this.delay(20);
this.alignAll();
}
我从未听说过bluej,但我可以看到您的setXPos
仅将新值分配给this.body
,尝试将所有值分配给所有3个对象。
public void setXPos(int newPos) {
this.xPos = newPos;
this.head.setXPos(newPos);
this.body.setXPos(newPos);
this.leg.setXPos(newPos);
this.alignAll();
}