Pergunta

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();
}
}
Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top