Question

What I'm trying to accomplish is adding 1 to the all the numbers in shipX array list, question is, how? I want to do this when the method move() is called, but how would I make this happen, as I'm new with arrays

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()
    {
    }
}
Was it helpful?

Solution

To start, you will have to move your arrays for points outside the local scope of paint() and into the class so that move() has access to the current values. You would increment in the move() method and call whatever routine you use to redraw your component.

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();
    }
}

Although I should point out that the repaint() method on JComponent does need to be called from the correct Swing thread, as pointed out in this answer.

If you are also trying to animate the movement, you can check out the Java Tutorial on Swing timers to call your move() method on a schedule. You could also use an ActionListener on a button to either control the Timer or on a button to move the object manually once per click.

OTHER TIPS

All you have to do is iterate through the array and modify the value of each index:

for (int i = 0; i < shipX.length; i++)
{
    shipX[i]++;
}

Increase the numbers one by one...

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]++;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top