dirac
dirac

Reputation: 309

repaint() in loop only called once - Java

I am trying to draw a grid on a JPanel but when I call the repaint method inside a loop it works only once. Here is my code:

public class Board extends JPanel{

    // --- Set Density of Grid ---
    public final int lines = 10;
    // ---------------------------

    public final int width =  600;
    public final int height = 600;

    public Point p1 = new Point(0,0);
    public Point p2 = new Point(0,0);

    public Board() {


        int c0 = width/lines;
        for (int j=0; j<2; j++){
            int c1 = width/lines;
            for (int i=0; i<lines; i++){

                if (j==0){
                    p1 = new Point(c1,0);
                    p2 = new Point(c1,height);
                }

                if (j==1){
                    p1 = new Point(0,c1);
                    p2 = new Point(width,c1);
                }

                c1 = c1 + c0;

                repaint();

            }
        }
    }


    public void drawGrid(Graphics g){
        g.drawLine(p1.x, p1.y, p2.x, p2.y);
    }

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);

        drawGrid(g);
        System.out.println("Inside");
    }

}

this is the output:

Inside

How can I call the paintComponent method multiple times when I use for loop?

Upvotes: 0

Views: 1043

Answers (1)

camickr
camickr

Reputation: 324098

The repaint() method just makes a request to the RepaintManager to paint components. The RepaintManager will then consolidate multiple requests into a single painting of the component to make the painting more efficient. So because all your requests are made within nanoseconds of one another in your loop, they all get consolidated into a single request.

If you want animation of some kind then you need to use a Swing Timer to schedule the animation. So each time the Timer fires you would increment the indexes by one.

Upvotes: 5

Related Questions