我想要完成的是将1
添加到shipX
数组列表中的所有数字,问题是,如何?我希望在调用方法move()
时执行此操作,但我将如何实现这一点,因为我是数组的新手
class Ship
{
public void paint(Graphics g)
{
int shipX[] = {500,485,500,515,500};
int shipY[] = {500,485,455,485,500};
g.setColor(Color.cyan);
g.fillPolygon(shipX, shipY, 5);
}
public void move()
{
}
}
答案 0 :(得分:4)
首先,您必须将数组移动到paint()
的本地范围之外的点并进入类,以便move()
可以访问当前值。您可以在move()
方法中增加并调用您用于重绘组件的任何例程。
class Ship
{
//make your polygon points members of the class
//so that you can have state that changes
//instead of declaring them in the paint method
int shipX[] = {500,485,500,515,500};
int shipY[] = {500,485,455,485,500};
//set these to the amount you want per update. They can even be negative
int velocityX = 1;
int velocityY = 1;
public void paint(Graphics g)
{
g.setColor(Color.cyan);
g.fillPolygon(shipX, shipY, 5);
}
public void move()
{
//add 1 to each value in shipX
for (int i=0; i<shipX.length; i++)
{
shipX[i] += velocityX;
}
//add 1 to each value in shipY
for (int i=0; i<shipY.length;i++)
{
shipY[i] += velocityY;
}
//call whatever you use to force a repaint
//normally I would assume your class extended
//javax.swing.JComponent, but you don't show it in your code
//if so, just uncomment:
//this.repaint();
}
}
虽然我应该指出repaint()
上的JComponent
方法确实需要从正确的Swing线程中调用,如this回答中所述。
如果您还尝试为动作制作动画,则可以查看Swing计时器上的Java Tutorial,按计划调用move()
方法。您还可以使用按钮上的ActionListener
来控制Timer
或按钮,以便每次点击一次手动移动对象。
答案 1 :(得分:3)
您所要做的就是遍历数组并修改每个索引的值:
for (int i = 0; i < shipX.length; i++)
{
shipX[i]++;
}
答案 2 :(得分:2)
逐一增加数字......
for (i=0; i<shipX.length; i++)
{
shipX[i]++; // same as shipX[i] = shipX[i] +1
}
for (i=0; i<shipY.length;i++)
{
shipY[i]++;
}