Ivan I. Ovchinnikov
Ivan I. Ovchinnikov

Reputation: 109

Java: Can't paint() every item from an array

I'm writing a game in which i need to paint bricks of a random color. This is my progress so far. I have a class of Brick, AllBricks, and Overridden paint method for JPanel:

private static class Brick {
    static int x;
    static int y;
    static Color color;

    Brick(int _x, int _y, Color _color){
        x = _x;
        y = _y;
        color = _color;
    }

    void paint(Graphics g) {
        g.setColor(Color.WHITE);
        g.drawRoundRect(x, y, BRICK_SIZE, BRICK_SIZE, BRICK_ARC_SIZE, BRICK_ARC_SIZE);
        g.setColor(color);
        g.fillRoundRect(x + 1, y + 1, BRICK_SIZE-2, BRICK_SIZE-2, BRICK_ARC_SIZE-1, BRICK_ARC_SIZE-1);
    }
private static class AllBricks {
    private ArrayList<Brick> bList = new ArrayList<>();

    AllBricks(){ bList.clear(); }

    void add (Brick b){ bList.add(b); }

    void paint(Graphics g) {
        if(bList.size()>0) {
            for (Brick brick : bList) brick.paint(g);
        }
    }
}
private static class GameField extends JPanel {
    @Override
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        allBricks.paint(g);
    }
}

And now, when I call my main loop, adding new blocks and trying to draw them, i only see the last added block, but not all of them...

private void loop()
{
    while (true) {
        delay.wait(1000);

        Brick b1 = new Brick(random.nextInt(WIN_WIDTH - BRICK_SIZE), random.nextInt(WIN_HEIGHT - BRICK_SIZE), COLORS.get(random.nextInt(COLORS.size() - 1)));
        allBricks.add(b1);
        mainField.repaint();
    }
}

Can you, please, help me save previously painted blocks on the screen?

Upvotes: 0

Views: 109

Answers (1)

Mein Name
Mein Name

Reputation: 527

Your brick x and y coordinate shoudn't be static. Since it's static all Bricks have one shared x and y value (so all Bricks are drawn at the same position)

Upvotes: 1

Related Questions