Question

What should I do to make my rectangle appear (and stay there until the app is closed)in different locations after application's restart? My code:

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.*;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;

class Rectangle extends JPanel {

    Random random1 = new Random(1000);

        int x1 = random1.nextInt(1000);
        int x2 = random1.nextInt(700);
        int x3 = random1.nextInt(600);
        int x4 = random1.nextInt(400);

         protected void paintComponent(Graphics g) 
    {
        for(int i=0; i<2; i++ ){
            int x1 = random1.nextInt(1000);
            int x2 = random1.nextInt(700);
            int x3 = random1.nextInt(600);
            int x4 = random1.nextInt(400);

            super.paintComponent(g); 

            //rectangle
            g.setColor(Color.red);
            g.fillRect(x2, x3, x1, x4);
        }
       repaint();
        }
 }

For now I have a rectangle appearing every sec somewhere else. I want it to change location but after restart of my app.

Was it helpful?

Solution

The basic answer is, don't randomise the position of your rectangles within the paintComponent method. This may be called any number of times during the execution of your program

class Rectangle extends JPanel {

    Random random1 = new Random(1000);

    private java.awt.Rectangle[] rects;

    public Rectangle() {
        rects = new java.awt.Rectangle[2];
        for(int i=0; i<2; i++ ){
            int x1 = random1.nextInt(1000);
            int x2 = random1.nextInt(700);
            int x3 = random1.nextInt(600);
            int x4 = random1.nextInt(400);
            rects[i] = new java.awt.Rectangle(x1, x2, x3, x4);
        }
    }

    protected void paintComponent(Graphics g) 
    {
        super.paintComponent(g); 
        g.setColor(Color.red);

        Graphics2D g2d = (Graphics2D)g;
        for(java.awt.Rectangle rect : rects){
            g2d.fill(rect);
        }
    }
}

Call super.paintComponent only once, one of it's jobs is to fill the background...

Don't call repaint or an method that might cause repaint to be called from within any paintXxx method, this sets up a nasty infinite loop which will suck your PC into a black hole

OTHER TIPS

You need to initialize your Random with the different seed each time. Try

 Random random1 = new Random(System.currentTimeMillis());

When Random is initialized with the same seed, it returns the same sequence of random numbers reach time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top