0

someone please help. I am trying to display an image of a brick layer by layer but when i run my code it just displays one brick at the position where the loop ends. Thanks for helping me out.

public class Game extends JApplet{

   Image [][] bricks = new Image[3][15]; 

   public void init()
    {
        Image brick = getImage(getDocumentBase(),"brick.png");

        for(int i =0; i < bricks.length; i++)
            for(int j = 0; j < bricks[0].length; j++)
                    bricks[i][j] = brick;


    }

    public void paint (Graphics g)
    {
       for (int i = 0; i < bricks.length; i++)
        for ( int j =0; j < bricks[0].length; j++)
            g.drawImage(bricks[i][j],i+85,j+30, this);

    }
}

1 Answer 1

1

This portion of code doesn't work as you apparently expect:

for (int i = 0; i < bricks.length; i++)
    for ( int j =0; j < bricks[0].length; j++)
        g.drawImage(bricks[i][j],i+85,j+30, this);

It does draw a grid of 15x3 images. But the design of the loop causes the position of the first painted brick (top-left) to be (85,30) and the last brick would be painted at (87,44). The problem is that each line and each row only differs by 1 pixel in position from the previous line/row.

You probably meant to do something like:

int imageWidth = bricks[0][0].getWidth(this),
    imageHeight = bricks[0][0].getHeight(this);

for (int i = 0; i < bricks.length; i++)
    for ( int j =0; j < bricks[0].length; j++)
        g.drawImage(bricks[i][j], i * imageWidth + 85, j * imageHeight + 30, this);

And creating the array is basically useless. Why not instead just paint the same image repeatedly without storing it multiple times in an array first? Using the matrix only makes things more complicated and slightly inefficient (the change is really minor due to the fact, that simply 45 copies of the same reference are stored, but why waste memory for no reason). In addition the code becomes harder to understand due to this.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.