Matt Martin Matt Martin - 1 month ago 20
Java Question

Java- random spawning of rectangles

Here's just part of my code which doesn't work as I want.When rectangle which is in loop is painted, it's every time painted at the same place, despite the fact I used random number for X and Y axis.I would like to paint rectangle 5 times (as it's set in loop) and each on random coords.If whole code is necessary, let me know please.Thank you!

public void paintComponent(Graphics g){
random=new Random();
rX=random.nextInt(500);
rY=random.nextInt(500);
super.paintComponent(g);

for(int i=0;i<=5;i++){
g.fillRect(rX,rY,20,20);
}


g.setColor(Color.red);
g.fillOval(x,y,20,20);

}

Answer

Currently your code only generates the coordinates only one time. (Thanks to Jon Skeet for pointing it out)

If you want it to paint five different trianlges you should move the call to random.nextInt inside the loop.

public void paintComponent(Graphics g){
    random=new Random();

    super.paintComponent(g);    

    for(int i=0; i<=4; i++){
        rX=random.nextInt(500);
        rY=random.nextInt(500);
        g.fillRect(rX,rY,20,20);
    }


    g.setColor(Color.red);
    g.fillOval(x,y,20,20);

}