1

I'm trying to create 100 random rectangles on the screen but it only paints 1 in the top left. Why does it do this and how do I fix it? It should repeat the paint rectangle process 100 times with the random x/y variables but it doesn't.

public class MazeGame extends JPanel {
    int x;
    int y;
    boolean Loc = false;
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawRect(x, y, 10, 10);
        this.setBackground(Color.RED);

    }

public void makeMaze() {
    for(int u = 1; u < 100; u++) {
        while(Loc == false) {
            int x = (int) (Math.random() * 100);
            int y = (int) (Math.random() * 100);
            System.out.println("x " + x + " " + "y " + y);
            repaint();
            Loc = true;
        }
        Loc = false;

    }
}
public void gui() {
    MazeGame game = new MazeGame();
    JFrame frame = new JFrame();
    frame.setSize(600, 600);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(game);
    game.makeMaze();

    frame.setVisible(true);
}
public static void main(String[] args) {
    MazeGame game = new MazeGame();
    game.gui();
}
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
ImGone98
  • 195
  • 8

1 Answers1

4

You never set x and y. Inside your loop you are defining a local x and y variable so the instance variables are never set. Remove the local variable declaration.

Dodd10x
  • 3,344
  • 1
  • 18
  • 27
  • Ok that was a stupid mistake, a fix to that is declaring the x/y in the paintComponent method, how would you stop it from erasing each time repaint is called? – ImGone98 Jan 23 '14 at 17:41
  • Well now you need to paint every rectangle. The way you are doing it now will only paint the most recent one. paintComponent starts with a fresh graphics object each time. If you want more than one to appear you will need to store the points and paint all of them at once. – Dodd10x Jan 23 '14 at 17:46
  • Your other option is to draw each rectangle to a BufferedImage you create and paint the buffered image inside paintComponent. – Dodd10x Jan 23 '14 at 17:47
  • I just put the random x and y variables into a for look inside paintComponent. Thank you – ImGone98 Jan 23 '14 at 17:50
  • You should compute them outside of the paintComponent method. Calculating random values on the event dispatch thread is bad, and it will slow down your repainting. You want to do as little as possible inside paintComponent(). That method is called often. – Dodd10x Jan 23 '14 at 18:59
  • You can store the rect. Objects in an array and then paint all in the *paintComponent()* method – java-love Jan 23 '14 at 21:16